Powershell (Version 2.0) remote execution of services with credentials - powershell

I want to start/stop apache and mysql services on remote machine by using powershell version 2.0 (Windows Server 2008). I found syntax for remote execution as follow:
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'").InvokeMethod("Stop-Service",$null)
But I have to provide credentials (DOMAIN_NAME\USERNANE and PASSWORD) also for this exceution. I am new to powershell and need help for correct syntax (example will be easy to understand and implement).

Get-WMIObject accepts the -Credential parameter. You shouldn't be keeping your credentials in plain text in your script, so you'll want to prompt for them.
$creds = get-credential;
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'" -credential $creds).InvokeMethod("Stop-Service",$null)
If you have PSRemoting enabled on the remote system, you can do this without WMI.
$creds = get-credential;
Invoke-Command -computername myCompName -credential $creds -scriptblock {(get-service -name myServiceName).Stop()};
Update based on comments
Since you're running this as a scheduled job, you should not be storing or prompting for credentials at all. Configured the scheduled job itself (via Scheduled Tasks) to run under the required user account, then either of the following should work:
# Your original code
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'").InvokeMethod("Stop-Service",$null)
# If you have remoting enabled
Invoke-Command -computername myCompName -scriptblock {(get-service -name myServiceName).Stop()};

Related

Invoke-WmiMethod - Quickly fix PsRemoting/WinRM problems (for Invoke-Command usage)

In the event you have computers that are unreachable with Invoke-Command either because WinRm is not running or PsRemoting is disabled here is a good, sure way I've found works everytime, in my environement at least:
$target_comp = "abc1234"
Invoke-WmiMethod -ComputerName $target_comp -Path win32_process -Name create -ArgumentList "powershell.exe -command Enable-PSRemoting -SkipNetworkProfileCheck -Force"
Invoke-WmiMethod -ComputerName $target_comp -Path win32_process -Name create -ArgumentList "powershell.exe -command winrm quickconfig -quiet"
do {
$testpsremoting = invoke-command -computername $target_comp -scriptblock {"test"}
} while (!$testpsremoting)
#REST OF CODE
Explanation :
-Declare variable of your computer name.
-Run the two commands to enable PsRemoting and setup WinRM via Invoke-WmiMethod.
*Since Invoke-WmiMethod returns instantly without WAITING for the commands to actually be done:
-Make a loop that runs until PsRemoting is enabled (until the test Invoke-Command works).
No more Invoke-Command problems! Enjoy and fine tune to your heart's content.
You could use Get-wmi to get the result directly
Get-WmiObject Win32_service -ComputerName $poste | select State,Name,DisplayName
Question changed to provide answer and useful fix for the community.

Powershell Remote Computer Session

I can run the following command from my desktop out of my HQ domain but I am unable to create a Remote Powershell session.
I have searched many posts and can not determine how to resolve this.
$TargetServer = 'RemoteComputer'
Get-WmiObject -Namespace "root\cimv2" -Class Win32_Process -Impersonation 3 -Credential RemoteDomain\username -ComputerName $TargetServer
Need this to work, please note that if i am logged into a management server in the remote domain the command works with my default nt permissions.:
$TargetServerSession = New-PSSession -Credential RemoteDomain\username -ComputerName $TargetServer
What's the Error you are getting? Maybe it's a credential thing, I kind of miss the get-credential part.
YourUser needs local Admin rights on the remote machine and you need to provide a password for the session.
You enter a PSSession by doing this:
# * Define name of remote machine
$TargetServer = "RemoteComputer"
# * Get a password prompt for the user 'YourUser' and store the creds
$Cred = (Get-Credential YourDomain\YourUser)
# * Create a PSSession for the Remote Computer using the Credentials you just provided
$PSSession = new-pssession -Computer $TargetServer -Credential $Cred
# * Enter the session
Enter-PSSession $PSSession
If this code is not working, then we need more infos.

Get-WmiObject doesn't work with IP but with FQDN

I have the following PowerShell script.
Code:
$User = "DOMAIN\user"
$PWord = ConvertTo-SecureString -String "somePassword" -AsPlainText -Force
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord
$query=...
Get-WmiObject -Computer 192.168.172.10 -Class Win32_ComputerSystem -ErrorAction Stop # Fails
Get-WinEvent -FilterXML $query -ComputerName 192.168.172.10 -Credential $Credential -ea stop # Works
Situation: I'm on a AD server with an IP like 192.168.1.1 and executing my script. [AD has access rights for all subnets and there is no firewall blocking access]
Issue: I want to query the following computer: server1 with ip 192.168.172.10 then this:
Get-WmiObject -Computer 192.168.172.10 -Class Win32_ComputerSystem -ErrorAction Stop # Fails
fails with an "RPC-Server is unavailable" error but this:
Get-WmiObject -Computer server1 -Class Win32_ComputerSystem -ErrorAction Stop # Works
works and this works too:
Get-WinEvent -FilterXML $query -ComputerName 192.168.172.10 -Credential $Credential -ea stop # Works
The server is in the same domain like the AD and Windows Firewall is for testing purposes disabled.
And a different server "server2" with ip 192.168.172.11 is working both ways with FQDN and ip.
Does anyone have an idea why in some cases (5 out of hundrets) the Get-WmiObject fails with ip but works with FQDN?
I searched about similar issues but all are about WinRM and are using commands like Invoke-Command. For sure WinRM first needs to be configured right in that case, but as far as I understood Get-WmIObject does not need WinRM. (I have not done any configuration tasks on all the computers).
The issue what you are facing is because of the reverse DNS records.
In your case, you might have multiple RDNS records for the same IP, causing the problem to be intermittent.
Check your reverse lookup zone and the the corresponding PTR records.
That should solve your issue.
Hope it helps.

Enabling Enable-PSRemoting on Powershell 1.0

This is in relation to http://www.computerperformance.co.uk/powershell/powershell_remote.htm . Currently, most of the machines in my Test environment are on Powershell 1.0. Under such a scenario, is there a way by which I can still manage to make remote calls via Powershell from one machine to another.
My ultimate motive is to start/stop/restart a windows service remotely using Powershell.
You're not going to be able to use PowerShell Remoting in 1.0, but you can use WMI or .Net ServiceController for this task.
$S = Get-WmiObject -Computer $Server -Class win32_service -filter "name='$ServiceName'"
$S.StopService()
$S.StartService()
In fact, if you have 2.0 on the client you're on, you can skip a couple of steps versus the way it's written on either of those posts by using Invoke-WMIMethod:
Invoke-WMIMethod -Name StopService -Computer $Server -Class win32_service -filter "name='$ServiceName'"
Invoke-WMIMethod -Name StartService -Computer $Server -Class win32_service -filter "name='$ServiceName'"
Note: for general remoting, you could set up an SSH server on each box and remote in that way (and set up PowerShell as the default shell), /n software has a pre-built solution around that.

Get-WmiObject with credential fails when within Start-Job scriptblock

I am successfully retrieving some information from Windows 2000 machines using the Get-WmiObjet cmdlet. These machines are not part of our domain so I am using the -Credential parameter to pass local administrator credentials.
I am now trying to run several WMI queries in parallel using Start-Job but I can't get even one query to work.
When I run the following:
Start-Job -initializationscript {$cred = get-credential -credential administrator} -scriptblock {gwmi win32_computersystem -ComputerName 10.1.2.3 -Credential $cred}
a job is created, I am prompted for the credentials, but the job never completes, its state is always "Running".
Of course:
C:\>$cred = Get-Credential -credential administrator
C:\>gwmi win32_computersystem -ComputerName 10.1.2.3 -Credential $cred
works just fine.
How do I get Get-WmiObject to run successfully within Start-Job with alternate credentials?
Thanks for your help.
Try this:
$cred = Get-Credential -Credential Administrator
Start-Job -scriptblock {Param ($cred) gwmi win32_computersystem -ComputerName 10.1.2.3 -Credential $cred} -ArgumentList $cred
Looks like the background job is blocked for input and has been running forever for that reason.