Use Connect-SPOService with Powershell 6 (core version) - powershell

I'm trying to connect to a sharepoint environment and I want to do that with Powershell version 6. Why? Eventually, I want to put the PS commands in a .net core 3 application. And as far as I know I cannot use PS5.1 in .net core.
It is about this powershell script:
Import-Module -Force -name Microsoft.Online.SharePoint.PowerShell;
Import-Module -Force -name Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;
$username = 'admin#shootme.com';
$password = 'right now';
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force);
Connect-SPOService -Url https://shootme.sharepoint.com -Credential $cred;
When I try this in the default PS 5.1 it just works fine. When I try this with PS 6.2.3, I get an error:
Connect-SPOService : The remote server returned an error: (400) Bad Request.
At line:1 char:1
+ Connect-SPOService -Url https://shootme.sharepoint.com -Credent ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Connect-SPOService], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.Online.SharePoint.PowerShell.ConnectSPOService
Does the newer Powershell have different syntax orso, of what am I doing wrong?
Also, maybe there is a way to run scripts in ps 5.1 when running them in .net core?

Have you tried connecting manually by removing the credentials portion and letting it prompt you for a login and test if that resolves successfully?
Edit: I do know you can also call powershell from a .bat like so:
powershell -version 2 .\xyz.ps1
But not knowing what you're going for exactly makes it tough to suggest if that's even a viable option.

Related

Copy-Item to networkpath: incorrect user name or password

I have a PowerShell v1 script, that is triggerd by a PLC. It should copy a file from the desktop of the embedded PC to a network path.
If I run the script manually it works just fine, but if the script is triggered by the PLC I will get the following error:
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
copy-item : The user name or password is incorrect.
Any tips, why I get this error, would be very much appreciated!
Thanks for your help #TheIncorrigible1 after reading your comment I found the problem!
The problem was, that the script started by the plc runs with another user than the manually started script.
So the workaround is to first start powershell with the correct credentials with another script. For example like so:
$usr = 'XXX'
$paswrd = 'XXX'
$securePassword = ConvertTo-SecureString $paswrd -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $usr, $securePassword
$args = "/path to your script"
Start-Process powershell.exe -Credential $credential -ArgumentList ("-file $args")
downside... password in plain text...

Access denied while running Windows Update using Powershell's Invoke-Command

I've been trying to setup a Powershell module that would remotely call Windows/Microsoft update on a server using Invoke-Command, then process the updates, and send everything back to the calling server so it can send an email report.
My issue comes when I try and call the downloader: Powershell seems to be requesting Elevated rights on the remote computer.
Here is a snippet of what I'm trying to run and fail:
Invoke-Command -ComputerName $Server -Credential $Credentials -ScriptBlock {
$UpdateSession = New-Object -ComObject "Microsoft.Update.Session"
Write-Progress -Activity "Updating" -Status "Checking for new updates"
$Criteria = "IsInstalled=0 and Type='Software'"
$Updates = $UpdateSession.CreateUpdateSearcher().Search($Criteria).updates
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $Updates
}
I know the issue isn't with remoting, as the first 4 commands work fine.
The $Credentials variable points to pre-defined credentials, which are Local Admin on the remote server.
When the script gets to the 5th line, $Downloader = $UpdateSession.CreateUpdateDownloader(), I get this error from Powershell:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException
+ PSComputerName : SERVER.sidlee.inc
What could be causing this exactly ?
Thanks in advance for the help!
As i just hit the same wall, and Google isn't of much help either, here is what i could dig up.
For the record, i am pretty much doing the same thing (using custom PS code to check remote systems for Windows Updates) but using WinRM over Python instead of Invoke-Command and also got stuck on Microsoft.Update.Searcher.Search() throwing a E_ACCESSDENIED error.
The UnauthorizedAccessException is indeed not related to Powershell but the underlying API.
I suspect Microsoft started cutting off impersonation in remote session in some recent update (Powershell v5?) as this was (and still is) working just fine on older Windows versions (e.g. Server 2012 with Powershell v3 or 2012 R2 with v4)
To get around this you will need to authenticate (on the remote server) prior to executing your stuff with a PSCredential object.
So Remote Auth -> Local Auth -> Run stuff for example using Start-Process -Credential ...
e.g.
$pass = ConvertTo-SecureString "PA$$W0RD" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential "User", $pass
Start-Process -Credential $creds powershell -ArgumentList "-Command & { ... whatever you want to do ... }"
Keep in mind that this poses a security risk as your password will be parsed in clear text, so don't do this over an
unencrypted channel!

Running Set-AzureRmAppServicePlan from Automation script (RunBook)

I'm trying to run Set-AzureRmAppServicePlan from automation runbook but getting
Set-AzureRmAppServicePlan : Run Login-AzureRmAccount to login. At
line:20 char:1
+ Set-AzureRmAppServicePlan -ResourceGroupName "...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Set-AzureRMAppServicePlan], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.WebApps.Cmdlets.AppServicePlans.SetAzureAppServicePlanCmdlet
Note that actual runbook authentication using Automation Credential is successful.
And I can run this script from local powershell using
Login-AzureRmAccount
Add-AzureRmAccount
Set-AzureRmAppServicePlan...
Is it possible at all to run this from automation without interactive login?
Thanks
Pavel
figure it out.. pretty simple instead of
Add-AzureAccount - which is used in sample runbook Get-AzureVMTutorial created automatically
need to use
Add-AzureRmAccount
for use with Azure Resource Manager cmdlet requests like
Set-AzureRmAppServicePlan
Leaving question / answer here.. might still help someone
If you are not using MFA, pls see the following cmds, replace 'yourPassword', 'yourUserName', 'yourEnvironment', 'yourSubscriptionId', 'yourTenantId' with your own message and put it to your script then you can login without interactive page.
$userPassword = ConvertTo-SecureString -String "yourPassword" -AsPlainText -Force
$psCred = new-object -typename System.Management.Automation.PSCredential -argumentlist 'yourUserName', $userPassword
$credential = Get-Credential -Credential $psCred
add-azureRmAccount -EnvironmentName 'yourEnvironment' -credential $credential -subscriptionId 'yourSubscriptionId' -tenant 'yourTenantId'

Connect-MsolService over WinRM fails

I am running a simple Powershell script over WinRM in order to get from Azure AD the list of user's licences. Here is the script itself:
$username = "admin#domain.onmicrosoft.com"
$password = "secret"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $(convertto-securestring $password -AsPlainText -Force)
Import-Module MSOnline
Connect-MsolService -Credential $cred -Verbose
$user = Get-MsolUser -UserPrincipalName $username
$status = $user.Licenses | ForEach-Object { $_.ServiceStatus }
$status | ForEach-Object { $_.ServicePlan.ServiceName + "|" + $_.ProvisioningStatus }
I have installed both Microsoft Online Services Sign-In Assistant and Azure Active Directory Module for PowerShell as described on this page https://technet.microsoft.com/en-us/library/jj151815.aspx#bkmk_installmodule
The script works fine if I run it locally on a machine running Windows.
But once I try to run it from Linux machine over WinRM the following exception is raised:
Connect-MsolService : Exception of type
'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was
thrown.
At line:5 char:1
+ Connect-MsolService -Credential $cred -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [Connect-MsolService], Mic
rosoftOnlineException
+ FullyQualifiedErrorId : 0x80070005,Microsoft.Online.Administration.Autom
ation.ConnectMsolService
However, if I run the script at least once locally on a Windows machine it starts working over WinRM. But after I reboot Windows it stops working again.
I have a strong feeling that when I run the script locally some background process is started and after that everything starts working over WinRM. But I could not identify what the process is.
I have installed Sing-In Assistant version 7.250.4556.0 (2/17/2014), Azure AD Module version 1.0.0 (1/19/2015).
It is very inconvenient to run the script locally each time Windows is restarted, so any help is appreciated.

Calling batch with user creds not working in powershell

I have a powershell script that contains the following
$username = 'username'
$password = 'password'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
start-process -FilePath $deploymentAppPath -Credential $cred
Yet when I execute this I get the following error.
start-process <<<< -FilePath $deploymentAppPath -Credential $cred
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
While I don't think it is probably obvious, my end goal here is to call the batch file with the user credentials that I specify.
I would start by removing the use of securestring. Some things just don't seem to work with it in my experiences.
It appears that your process is local, so you're not transmitting the u/p over the wire. Is the securestring really neccessary (considering that the u/p is in the script and available to whoever has perms to the script)?
I believe you do not have the right version of windows powershell to use the start-process command. I ran this and it worked other than the obvious -FilePath error that I did not set. Where as you seem to be getting the basic 'command does not exist' exception. To check your version number use the get-host cmdlet. Run get-host | select version and if it outputs 1.0 to console you should go Here to get a 2.0 version.