I received a comment yesterday on most popular post of my blog(https://techibee.com/powershell/startstoprestart-service-on-remote-computer-with-powershell/693) asking for a way to start, stop, restart services using alternate credentials. I thought about it for some time and came up with below script.
Note that I am not going to use built-in cmdlets like get-service, start-service, stop-service in here since they don’t have an option to provide alternate credentials. Instead I am replying on WMI class Win32_Process which allows me to pass the credentials when I use through Get-WMIObject cmdlet.
Here is the code.
$credential = Get-Credential $myservice = Get-WmiObject -Class Win32_Service -ComputerName SERVER1 ` -Credential $credential -Filter "Name='spooler'" $myservice.stopservice()
It is that simple. Similarly if you want to start the service just use “startservice” method like given below.
$credential = Get-Credential $myservice = Get-WmiObject -Class Win32_Service -ComputerName SERVER1 ` -Credential $credential -Filter "Name='spooler'" $myservice.startservice()
Hope this helps and this article also gains some popularity.
Comments on this entry are closed.
An alternative, if you have PowerShell remoting enabled is to use Invoke-Command:
invoke-command {Restart-Service spooler} -comp Server1-cred $credential
This is especially handy if you want to manage a service on multiple machines.
Great blog here! Also your web site loads up fast!
What host are you using? Can I get your affiliate link to your host?
I wish my site loaded up as fast as yours lol
(get-service -computername server service).stop()
(get-service -computername server service).start()
get-service -computername server service | stop-service
etc…you get the point.
Jeffery Hicks (MVP), That will work unless the service in question is “WinRM” (The one used for remoting). There are certain situations (like creating new PSConfigurations on remote in different domain) where the WinRM service needs to be restarted for the new configuration to become available.
@Sitaram… Did you come up with the script for Laxmi..?
which script? Please add more details.
Great Help ! Thanks Buddy ! it is Awesome !
Connecting to remote server Server1 failed with the following error message : The WinRM client cannot process the request. Default authentication may be used with an IP
address under the following conditions: the transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure
TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more information on how to set TrustedHosts run the following command: winrm help config. For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Server1:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotUseIPAddress,PSSessionStateBroken
Are you using IP addresses to connect?