Set-Service : A parameter cannot be found that matches parameter name 'Credential' - powershell

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"
}

Related

Running Powershell script using inline admin credentials to start and stop windows services

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

Use Connect-SPOService with Powershell 6 (core version)

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.

How to Install Windows Updates on Remote Computer with PowerShell

I'm trying to install Windows Updates on a Remote Computer with this command:
$InstallSplat = #{
AcceptAll = $true
SendReport = $true
IgnoreReboot = if ($Reboot) { $false } else { $true }
PSWUSettings = #{
SmtpServer = "my mail server"
From = "myfrom <myfrom#myfrom.com>"
To = "myto <myto#myto.com>"
Port = 25
}
}
Invoke-Command -ComputerName $_ -Credential $cred -AsJob -ArgumentList $InstallSplat -ScriptBlock {
param([hashtable]$InstallSplat)
Import-Module PSWindowsUpdate
Install-WindowsUpdate #InstallSplat
$Error | out-file C:\install\installwinupdate.log -Append
}
I pass a credential Object with domain admin privileges in $cred but I still always get this error
Install-WindowsUpdate : Access denied (Ausnahme von HRESULT: 0x80070005 (E_ACCESSDENIED)) In Zeile:4 Zeichen:25
+ Install-WindowsUpdate #InstallSplat
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WindowsUpdate], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,PSWindowsUpdate.GetWindowsUpdate
The Command Install-WindowsUpdate itself does not have a credential parameter I could use. The Command needs to run in an elevated PowerShell, but I use an elevated PowerShell when starting this command on my Computer.
I Also tried creating a New-PSSession with my $cred and run Invoke-Command -Session $session instead of Invoke-Command -ComputerName $_ with the same result.
Does anybody know what's happening here? Why do I get Access denied?
It can't have anything to do with passing the $InstallSplat because the same thing happens if I don't pass any parameter at all and write the parameters and their Values directly at the command instead of splatting.
The Problem was, that you can't Download or Install Updates on a machine from another remote machine. Here's a list what you can or can't do remotely when it comes to Windows Updates
The solution is, to create a scheduled task on each server you want to install updates from a remote script, and start that task.
luckily, when you use the PSWindowsUpdate module, you don't have to do that yourself, you can just use Invoke-WUJob (formerly Invoke-WUInstall) which does the trick for you.
I used it like so ($ServerData.Value contains a list of my Servers) and it works like a charm. It creates a scheduled task on each server, and runs them immediately, if you add the -RunNow Parameter.
invoke-WUJob -ComputerName $ServerData.Value -Script { Import-Module PSWindowsUpdate ; Install-WindowsUpdate -AcceptAll -SendReport -IgnoreReboot -PSWUSettings #{From='xy';Port=25;SmtpServer='xy';To='xy'} | Out-File C:\install\PSWindowsUpdateLog.txt -Append} -Confirm:$false -verbose -RunNow
Note that what you specify as a script block in -Script will be pasted to -Command " <here> " in your scheduled task, so you should work with ' inside -Script.

Script creates local admin and then adds it to service with different password

I have a script that creates a local user account, sets the password, adds the local account to Administrators group, and then sets a service to run as this account. The problem is when trying to restart the service I get an error:
Error 1069: The service did not start due to a logon failure.
I found out that when I manually set the password, I'm able to start the service.
The problem seems to be how the password is passed to the $service.Change($null,...,$password,...,$null) method.
$name = $env:COMPUTERNAME
$computer=[ADSI]"WinNT://$name"
$newuser = $computer.Create('User','newuser')
$password = "Password1"
$newuser.SetPassword($password) #this works
$newuser.SetInfo()
$admin = "Administrators"
$group=[ADSI]"WinNT://$name/$admin,Group"
$group.Add($newuser.path)
$service = Get-WmiObject Win32_service -filter "name='ServiceName'"
$service.Change($null,$null,$null,$null,$null,$null,".\newuser",$password,$null,$null,$null) #this doesn't. Password has not changed.
Restart-Service -Name $service.Name
Restart-Service : Service 'Service Name (ServiceName)' cannot be started due to
the following error: Cannot start service ServiceName on computer '.'.
At C:\Users\superfoo\Documents\Scripts\ServiceUpdate.ps1:68 char:3
+ Restart-Service -Name $serviceControl
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Restart-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.RestartServiceCommand
The $password works while creating the account but not for setting the password on the service. I am running the script as administrator.
OS: Windows 10 (x64)
Powershell: Version 5.0.10586.122

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.