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.
Related
I am trying to use a powershell script to change the login credential of a service. As per this Microsoft documentation (example 8), I am using the following code:
$credential = Get-Credential
Set-Service -Name serviceName -Credential $credential
When I run the script, I am prompted for a username and password, which I enter, but then the following error results:
Set-Service : A parameter cannot be found that matches parameter name 'Credential'.
At line:2 char:28
+ Set-Service -Name serviceName -Credential $credential
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
What might be causing this? This machine is not on a domain, but I am logged on as a local administrator, and running powershell as an administrator. I have permissions to change these services and can enter the login details normally via the usual Services GUI.
The Credential parameter only exist for PowerShell version 6+ (which is out of support).
Probably you are using a version from before PowerShell 6 (most probably 5.1 which is still the main version in Windows 10 and 11).
See below Set-Service in:
PowerShell 5.1
PowerShell 6.0 (Archive)
PowerShell 7.0
Run $PSVersionTable.PSVersion, to your PowerShell version.
If you run (Get-Help -Name Set-Service).Parameters.parameter.Name, you'll find all the available Parameters in the active version.
If you're running 5.1 or older, the Get-Help -Name Set-Service -Parameter Credential should return the error "No parameter matches criteria.".
Installing or updating to PowerShell 7.X is as easy as running winget install Microsoft.PowerShell.
Why don't you want to use:
sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"
If you want the user to enter a username/password each time, then you can use:
$cred = Get-Credential
$username = $cred.username
$password = $cred.GetNetworkCredential().password
&sc.exe config "[servicename]" obj= "$username" password= "$password"
if you need to check that the username and password are valid, then you can use:
$currentdomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($currentdomain,$username,$password)
if ($domain.name -eq $null) {
write-host "Authentication failed - please verify your username and password."
exit
}
else {
write-host "Successfully authenticated with domain $domain.name"
}
I have access as an admin on a machine and I have to Start, Stop and Restart some of the window services using the Powershell script. We don't want to have UAC prompt while running the script because only one user would have access to that machine. Also due to some specific requirements, we have to have run that script file by adding the admin credentials inside it.
Along with other solutions I have tried so far, the one close to what I am looking for is as follows
$username = "Domain\user"
$password = ConvertTo-SecureString "myPassword" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)
Set-Service -Name Spooler -Status Running -PassThru -Credential $psCred
But I am getting following error.
Set-Service : A parameter cannot be found that matches parameter name
'Credential'. At line:6 char:53
+ ... t-Service -Name Spooler -Status Running -PassThru -Credential $psCred
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Update 1 (Trying suggestion)
Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername myComputerName
[myComputerName] Connecting to remote server myComputerName failed
with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command on the destination to analyze
and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (myComputerName:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionStateBroken
Update 2
I had to enabled PSRemoting on machine using command Enable-PSRemoting -Force -SkipNetworkProfileCheck so Invoke-Command can execute but after repeating the command Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername localhost I got following error
[localhost] Connecting to remote server localhost failed with the
following error message : Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
Running the same set of command in elevated powershell window is working fine.
Can you please guide me in the right direction considering I am newbie in the Powershell world.
As mentioned in the official documentation of Set-Service
Can you try like this?
$Cred = Get-Credential
$hostname = "$env:computername.$env:userdnsdomain"
Write-Host $hostname
Invoke-Command -ComputerName $hostname -Credential $Cred -ScriptBlock{ Start-Service -Name Spooler}
Also if you don't want to prompt for the credentials then you can store the credentials in the Windows credentials manager and get it from their in your PowerShell script. Refer to this answer for using credential manager with 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.
I am trying to invoke a PowerShell command on a remote computer. I'd like to request a certificate from an in-house CA. If I run the following command directly on the remote PC the operation is successful:
Get-Certificate -Template 1.3.6.1.4.1.311.21.8.9612972.3074733.7357589.1249582.14248002.117.5480590.5436517 -Credential $cred -Url ldap: -CertStoreLocation Cert:\LocalMachine\My
When I run the following command from a remote computer on the same domain I get the WIN32: 87 error shown below. I have googled the error extensively and cannot figure out the issue (fyi.. I have mitigated the double hop issue earlier in my script by using Enable-WSManCredSSP).
$user = 'ABCCOmpany\<password>' #We are using the local machine's Administrator account
$password = ConvertTo-SecureString '<password>' -asplaintext -force
$credential = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $user, $password
$RequestAndReceiveCertificateSuccessful = Invoke-Command -Session $s -ScriptBlock{param($cred) Get-Certificate -Template 1.3.6.1.4.1.311.21.8.9612972.3074733.7357589.1249582.14248002.117.5480590.5436517 -Credential $cred -Url ldap: -CertStoreLocation Cert:\LocalMachine\My} -ArgumentList $credential
Error:
The parameter is incorrect. 0x80070057 (WIN32: 87 ERROR_INVALID_PARAMETER)
+ CategoryInfo : NotSpecified: (:) [Get-Certificate], Exception
+ FullyQualifiedErrorId : System.Exception,Microsoft.CertificateServices.Commands.GetCertificateCommand
+ PSComputerName : Agent3
I'm trying to connect to amazon windows instance using powershell. I'm following the steps from the below link:
Execute powershell script remotely on Amazon EC2 instance from my local computer
http://barakme.tumblr.com/post/89748667258/windows-remote-execution-with-powershell-and-winrm
http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/connecting_to_windows_instance.html
I cannot make this to work. I'm new Amazon CLI, I've been struggling for the past few days to connect to my windows instance which is already running.
I keep getting the same error each time. Am I missing out something?
enable-psremoting -force
set-item wsman:\localhost\Client\TrustedHosts -value "*" -force
$password = convertto-securestring -asplaintext -force -string "MY_PASSWORD_GOES_HEREr"
$credential = new-object -typename system.management.automation.pscredential -argumentlist "MY_USERNAME", $pa
ssword
$session = new-pssession x.x.x.x -credential $credential
new-pssession : [x.x.x.x] Connecting to remote server x.x.x.x failed with the following error message : WinRM
cannot complete the operation. Verify that the specified computer name is valid, that the computer is accessible over
the network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By
default, the WinRM firewall exception for public profiles limits access to remote computers within the same local
subnet. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:12
+ $session = new-pssession x.x.x.x -credential $credential
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionOpenFailed