Powershell stop-service error: cannot find any service with service name - powershell

I'm working on a script to deploy vendor software to a large environment. The first step is to stop the services in question. The script executes fine in our test environment, but I'm not an admin in the production environment so I'm convinced it's a permissions issue. I can't get admin rights to the prod environment so I need to try to find out anything that I may need to set to grant permissions to stop services remotely. I'm issuing the following command to stop services:
Stop-Service -InputObject $(Get-Service -Computer $destination.Server -Name ("moca."+$destEnv))
When I run the script I get:
Cannot find any service with service name 'moca.WMSPRD'.
+ CategoryInfo : ObjectNotFound: (moca.WMSPRD:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
+ CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StopServiceCommand
The service definitely exists and if I rdp into the target box and issue the stop-service command locally it will execute. So there is something preventing me from stopping the service remotely. Any ideas?
Edit:
A coworker suggested using WMI so tried replacing the Stop-Service line with:
(Get-WmiObject -computer $destination.Server Win32_Service -Filter ("Name='moca."+$destEnv+"'")).InvokeMethod("StopService",$null)
and I get:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

If you know the exact service name you can try this
(Get-WmiObject -computerName $_.name Win32_Service -Filter "Name='moca'").StopService()
Here im assuming that the service name is moca

Is DCOM working on the remote computer? I know how to do it with remote powershell, which uses wsman:
invoke-command comp001 { stop-service adobearmservice }

Related

PowerShell 5.1 What is wrong with my New-PSSession syntax

Environment:
PowerShell 5.1
Windows 2016 Standard
Windows 10 Pro
Just asking here if syntax is fundamentally correct...
$hostSession = New-PSSession -ComputerName $hostName -Credential $cred
$versionFolder = "c:\temp"
$sspLatestVer = Invoke-Command -Session $hostSession -ScriptBlock { param($path) (Get-ChildItem $path | Sort-Object LastWriteTime -Descending | Select-Object -First 1).Name } -ArgumentList $versionFolder
Update:
The following works on one machine but not on another:
$versionFolder = "\\COMPUTER01\c$\temp"
$sspLatestVer = (Get-ChildItem $versionFolder | Sort-Object LastWriteTime -Descending | Select-Object -First 1).Name
Error Message for machine that doesn't work
Get-ChildItem : Cannot find path '\\COMPUTER01\c$\temp' because it does not exist.
At C:\temp\candidate2.ps1:24 char:18
+ $sspLatestVer = (Get-ChildItem $versionFolder | Sort-Object LastWrite ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\COMPUTER01\c$\temp:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
OP Error Message:
New-PSSession : [COMPUTER01] Connecting to remote server COMPUTER01 failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090311 occurred while using
Kerberos authentication: We can't sign you in with this credential because your domain isn't available. Make sure your device is connected to your organization's network and try again. If you previously signed in on
this device with another credential, you can sign in with that credential.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
At C:\Users\RSTEST\Documents\candidate2.ps1:17 char:16
+ ... hostSession = New-PSSession -ComputerName $hostName -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\RSTEST\Documents\candidate2.ps1:19 char:41
+ $sspLatestVer = Invoke-Command -Session $hostSession -ScriptBlock { p ...
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
Remove-PSSession : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\RSTEST\Documents\candidate2.ps1:20 char:24
+ Remove-PSSession -Name $hostSession
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Remove-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RemovePSSessionCommand
Two issues here:
First, see WinRM cannot process the request. Error 0x80090311
If the remote system is in the same domain, and you are already logged in with a domain account that is an administrator on that system, then there would be no need to specify a credential for New-PSSession
If the systems are in different forests that have a trust with each other, note that there is a need to use the fully qualified domain name (FQDN) of the remote host for Kerberos authentication to function correctly.
Second, regarding:
$versionFolder = "\\COMPUTER01\c$\temp"
Note that remote sessions normally do not have access to network shares, even when presumably running under the credentials of an administrative user.
This is known as the "second hop problem". There have been various posts about it:
https://learn.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-5.1
https://devblogs.microsoft.com/scripting/enable-powershell-second-hop-functionality-with-credssp/
This may work from COMPUTER01 itself, since it could be aliased to local drive access.

Restart network PC's services using PowerShell [duplicate]

This question already has answers here:
Stopping & Restarting Services Remotely Using Set-Service
(3 answers)
Closed 3 years ago.
I need to restart services of a LAN Computer using IP Address. I have this researched:
Restart-Service -ComputerName \\10.10.11.16 -ServiceName IETCQRService dnsCache
and this is the error I get:
Restart-Service : A parameter cannot be found that matches parameter name
'ComputerName'.
At line:1 char:17
+ Restart-Service -ComputerName \\10.10.11.16 -ServiceName IETCQRServic ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Restart-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.RestartServiceCommand
I need to use the IP Address because the computer names are the same, they just differ on the IP Address.
EDIT
I have used the suggestion but I get this error now:
PS C:\WINDOWS\system32> Get-Service -ComputerName 10.10.11.16 -Name "IETCQRService" | Restart-Service
Get-Service : Cannot find any service with service name 'IETCQRService'.
At line:1 char:1
+ Get-Service -ComputerName 10.10.11.16 -Name "IETCQRService" | Restart ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (IETCQRService:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
So far as I know, there is no -ComputerName parameter on the Restart-Service command. Instead, you could use something like this:
Get-Service -ComputerName 10.10.11.16 -Name "IETCQRService" | Restart-Service
You could use both the IP address or the computer name in the Get-Service command
Note As pointed out in the comments, this option isn't viable going forward as it is being removed from PowerShell version 6+.

PowerShell Stopping and Starting Services with Server names masked by DNS Alias

I have a simple PowerShell that accepts a file as a parameter that contains Server-Name, Service-Name and Timeout specified in seconds and the powershell stops/starts the services based on the command. I have 10 servers where application related services are configured and I'm using Workload automation capabilities to run this code on any server with the same parameter file and powershell present on all 10 servers.
All of this works fine with server names hardcoded in the param file. We have n+2 Infrastructure, and I created DNS Aliases for all the 10 servers to make Active-Standby switchover little easy. Now the problem comes with stop/start script. Ex: If the script gets invoked in Server 7, all the services will be shutdown except for the ones in Server 7 and I get below error:
Get-Service : Cannot find any service with service name
'Application-Server7'. At line:1 char:1
+ Get-Service -ComputerName app7test -Name Application-Server7
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Application-Server7:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
I just tested one-liner command using PowerShell ISE on the computer "appnewora79" and below are the results.
This works fine:
Get-Service -ComputerName appnewora79 -Name Application-Server7
Status Name DisplayName
------ ---- -----------
Stopped Application-Ser... Application-Server7
This fails:
Get-Service -ComputerName app7test -Name Application-Server7
Get-Service : Cannot find any service with service name 'Application-Server7'
At line:1 char:1
+ Get-Service -ComputerName app7test -Name Application-Server7
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Application-Server7:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Any suggestions to overcome this, please?
I tried below as well:
It all works when the server name is hardcoded. If I change it to DNS Alias name then Get-Service fails on the server where it is executing while fetching service details only related to the same server.
On the Server-1, if I run below commands, they all work fine
Get-Service -ComputerName servername1
Get-Service -ComputerName servername2
Get-Service -ComputerName servername3
If I update the above command with server dns alias and execute them on Server-1, then only the first command fails, i.e.. the command with the same server name masked with DNS fails, If I run the same commands on server 2, then the second one alone fails
Get-Service -ComputerName dnsalias1
Get-Service -ComputerName dnsalias2
Get-Service -ComputerName dnsalias3
I tried, test-connection with DNS alias names and they go thru fine. Tried Get-WmiObject -Class WIN32_service with computer name masked as DNS alias and it goes thru fine. I'm lost as to what could be the issue.
Below is the error message with Get-Service alone:
Get-Service : Cannot open Service Control Manager on computer 'dnsalias1'. This operation might require other privileges.
At line:5 char:1
+ Get-Service -ComputerName dnsalias1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
I found a kind of different way to resolve this as per suggestion received in PowerShell Google+ forum.
I used Resolve-DnsName to get hold of IP4Address of the server and then passed it for stopping and starting windows services and this works.

PowerShell remote restart service running from a TFS build error

I have a TFS build definition contains a PowerShell Script build step. I would like to run the following command on a remote computer(DEVWS45PC) which should restart the service named StartSeleniumGridHub:
winrm s winrm/config/client '#{TrustedHosts="DEVWS45PC"}'
Restart-Service -InputObject $(Get-Service -Computer DEVWS45PC -Name StartSeleniumGridHub)
This gives me this error:
##[error]Get-Service : Cannot find any service with service name 'StartSeleniumGridHub'.
At E:\builds_2017\killBrowsersOnAllNodesAndRestartHub.ps1:43
char:36
+ Restart-Service -InputObject $(Get-Service -Computer DEVWS45PC -Name StartSe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (StartSeleniumGridHub:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Restart-Service : Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At E:\builds_2017\killBrowsersOnAllNodesAndRestartHub.ps1:43
char:34
+ Restart-Service -InputObject $(Get-Service -Computer DEVWS45PC -Name StartSe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Restart-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RestartServiceCommand
I can run this script without any problem from any of my computers. Note that 'DEVWS45PC' is truly set as a trusted host on the TFS build agent computer, so it's not the problem.
I have no clue what is the problem. Maybe authentication problems?
You could manually RDP to the remote machine DEVWS45PC with your build service account and run the powershell script.
Most likely lacking of permissions of your build service account(Due to could not find the service). Suggest you add the service account to your local Administrator group on the remote machine DEVWS45PC and try again.
Also make sure you are using the PowerShell on Target Machines task instead of powershell task in the build definition.

Why do Powershell queries on remote machine throwing access denied errors?

I'm getting such errors from the PowerShell ISE when I execute simple PowerShell queries on my machine connecting to a remote machine:
Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:8 char:43
+ $WmiOS = Get-WmiObject <<<< -Class Win32_OperatingSystem -ComputerName $targetComputer -credential $credential
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
You cannot call a method on a null-valued expression.
At line:9 char:45
+ $WmiOS.ConvertToDateTime <<<< ($WmiOS.LastBootUpTime)
+ CategoryInfo : InvalidOperation: (ConvertToDateTime:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
However, the same queries would work on my other team member's machine (or on any other machine) without any issues.
An example of the script that we're trying to execute:
$WmiOS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $targetComputer -credential $credential
$WmiOS.ConvertToDateTime($WmiOS.LastBootUpTime)
Any ideas?
Try adding the below flags to the Get-WmiObject command:
-Authentication PacketPrivacy -Impersonation Impersonate
Check firewall on remote machine and/or credentials to be in administrators local group of remote computer
Make sure the script you are running is not located on the server itself. It is common practice for people to host their powershell scripts on the server in order to have them in various locations. If your scripts are local, then you should be able to shut down the machine.