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

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.

Related

PowerShell run Command as different User when Credential Parameter is missing

I need to run a common PowerShell command to trigger a Group Policy Update "gpupdate" on a remote computer out of a workflow.
The workflow runs in a system user context, which do not have the local admin permissions on the clients to force a remote "gpupdate".
For that reason, I import a PowerShell credential secure string with "Import-CliXml" to run that statement in scope of a user which is local admin on the clients.
But, the command I want to use, don't support the native credential parameter. And I need to use a parameter for the remote client.
Invoke-GPUpdate -Computer $client -RandomDelayInMinutes 0
I tried many approches from the internet, but it won't work for me:
Start-Process powershell.exe -Credential $credentials -ArgumentList $ProcessCommand -WorkingDirectory $env:windir -NoNewWindow -PassThru
Start-Process powershell.exe -wait -Credential $credentials -ArgumentList "-command &{Start-Process Powershell.exe -argumentlist '$($cmnd)' -verb runas -wait}"
If I test to send the remote gpupdate out of a PowerShell console started with a user which is local admin on the remote client, it works.
Did anyone has a solution for this problem?
Many thanks!
When I connect to remote computers using PowerShell to execute commands on those computers I normally run the following. I've left an example of my code for you to use to execute Invoke-GPUpdate
#Local Host Computer
#$RequestingServer = $env:COMPUTERNAME
#Server List From Text File
#$ServerList = Get-Content 'C:\temp\servicetest\servers.txt'
#Server List In Script
$ServerList = 'Computer1','Computer2','Computer3','Computer4'
#Domain Admin Account
[STRING]$DomainAccountName = (whoami)
[STRING]$DomainAccountName = $DomainAccountName.Split("\")[1]
[STRING]$DomainAccountPassword = "Password01" #Obviously Change Password
$DomainAccountSecurePassword = $DomainAccountPassword | ConvertTo-SecureString -AsPlainText -Force
$DomainCredentials = New-Object System.Management.Automation.PSCredential -ArgumentList $DomainAccountName, $DomainAccountSecurePassword
#Local Server Admin Account
[STRING] $LocalUser = "Administrator" #Obviously Change Account
[STRING] $LocalPassword = "Password01" #Obviously Change Password
$LocalSecurePassword = $LocalPassword | ConvertTo-SecureString -AsPlainText -Force
$LocalCredentials = New-Object System.Management.Automation.PSCredential -ArgumentList $LocalUser, $LocalSecurePassword
#If running on multiple computers / servers etc. - - See Lines 5 and 8
ForEach($ComputerName in $ServerList) {
#Update Windows Something Locally - See Line 2
#$DomainSession = New-PSSession -Computername $RequestingServer -Credential $DomainCredentials
#Update Windows Something Remotely - See Lines 5 and 8
$DomainSession = New-PSSession -Computername $ComputerName -Credential $DomainCredentials
Invoke-Command -Session $DomainSession -ScriptBlock {
#Some commands need the computername currently using localhost...
$GPUpdateServer = $Using:ComputerName
#$GPUpdateServer = $Using:RequestingServer
# enter code of what you plan to do...
Invoke-GPUpdate -Computer $GPUpdateServer -RandomDelayInMinutes 0
}
} End of ForEach Statement
#If running on multiple computers / servers etc. - - See Lines 5 and 8
ForEach($ComputerName in $ServerList) {
#Update Windows Something Locally - See Line 2
#$LocalSession = New-PSSession -Computername $RequestingServer -Credential $LocalCredentials
#Update Windows Something Remotely - See Lines 5 and 8
$LocalSession = New-PSSession -Computername $ComputerName -Credential $LocalCredentials
Invoke-Command -Session $LocalSession -ScriptBlock {
#Some commands need the computername currently using localhost...
$GPUpdateServer = $Using:ComputerName
#$GPUpdateServer = $Using:RequestingServer
# enter code of what you plan to do...
Invoke-GPUpdate -Computer $GPUpdateServer -RandomDelayInMinutes 0
}
} End of ForEach Statement
Facing this problem more in detail, I tested the approach above with the remote PowerShell session. This needs some more preparation in domain for deploying all necessary GPO settings to all clients to make WinRM work.
The remote PowerShell approach works, but I found out that the Invoke-GPUpdate command is only available on clients which have RSAT installed. So only works on a few in clients in IT department.
$Session = New-PSSession -Computername $clientname -Credential $domainAccountWithLocalAdminRights
Invoke-Command -Session $Session -ScriptBlock { Invoke-GPUpdate -Computer $env:ComputerName -RandomDelayInMinutes 0 }
$Session | Remove-PSSession
I switched over to a different approach which worked for me without using remote PS sessions. Completely silent on the client, you will find the triggered gpupdates only in Windows event viewer.
Invoke-Command -ComputerName $clientname -ScriptBlock { gpupdate } -Credential $domainAccountWithLocalAdminRights

Run Get-ClusterGroup on remote server using Central server

I have a centralized server from which i can run the following PowerShell command to get the clustergroup of cluster servers.
Enter-pssession -computername (ip-address) -credential (domain user)
And it prompts me to enter password then i get the session and execute
get-clustergroup
Okay till this it is fine.
Now i wanted to make this fully automated by converting in to a PowerShell script
The following commands works well when i run it in Powershell ISE and gets me the output of get-clustergroup
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$user = "domain\user"
$cred = New-Object System.Management.Automation.PSCredential ($user,$password)
Enter-PSSession -ComputerName IP.Add.RE.SS -Credential $cred
get-clustergroup
but when i save the about script and run with PowerShell i get the following error.
get-clustergroup: the cluster service is not running
I want to automate the process by writing script to get get-clustergroup output of four cluster servers.
i am new to PowerShell scripting. how can i save the output?
Instead of creating a session to the other server, you can run the following which will run the command on the remote computer and return the output to your console:
Invoke-Command -ComputerName <IPAddress> -ScriptBlock { Get-ClusterGroup } -Credential $cred
You can store that output into a variable if you wish for future retrieval.
Since -ComputerName can accept an array object, you can modify your command to include all four of your servers. Below shows how to use all of your computer names and store the output in the variable $Output:
$Output = Invoke-Command -ComputerName "Server1","Server2","Server3","Server4" `
-ScriptBlock {Get-ClusterGroup} -Credential $cred
$Output
Your computer names could also be stored in a variable as an array. Then that variable can be used in your -ComputerName parameter:
$Computers = "Server1","Server2","Server3","Server4"
Invoke-Command -ComputerName $Computers -ScriptBlock { Get-ClusterGroup } -Credential $cred
See Invoke-Command for more information.

How to use invoke-command in powershell, to run a script on remote machine

Is it possible to use Invoke-Command in PowerShell to run a script on a remote machine?
I have tried :
Invoke-Command -ComputerName $MyPC -Credential $mycreds -ScriptBlock {
& "C:\Users\MyPC\Desktop\scripts\Script1.ps1"
}
which returns
script1.ps1 is not recognized as the name of a cmdlet
The scenario here is, I have some scripts on a remote folder, and I need to use Invoke-Command or some other ways to run the script on a remote machine.
Also, how to write if I want to pass some parameters for script1.ps1? Thanks in advance!
Instead of this:
Invoke-Command -ComputerName $MyPC -Credential $mycreds -ScriptBlock {& "C:\Users\MyPC\Desktop\scripts\Script1.ps1"}
Try this:
Invoke-Command -ComputerName $MyPC -Credential $mycreds -FilePath C:\Users\MyPC\Desktop\scripts\Script1.ps1
to avoid confusion with filepaths on local machines/remote machines; i always run stuff from smb-shares; you can enter UNC as filepath... eg:
-FilePath \server\Netscripts\script.ps1

Privileges ACLs error when run remotely. invoke-command

I have a very simple script that works perfectly fine on a server, where I log on into the server and run it.
invoke-command -scriptblock { & snacfg workstation Computer /delete}
However, when I try to do it remotely, I receive "You do not have the privileges required to set system ACLs on files."
invoke-command -ComputerName SERVER -scriptblock {snacfg workstation COMPUTER /print} -Credential ""
I have also tried to call it remotely but get the same error message.
Start-Process powershell.exe -ArgumentList \\SERVER\c$\users\USERNAME\desktop\SCRIPT.ps1 -Credential ""
Any ideas?
Thanks.
You should probably leave the -Credential "" away, By adding this you bassicly telling it to run without an account I think. So either Remove it entirely so it will be run under the account of the current user, or declare the credentials like in the following 2 examples.
Option 1
$creds = Get-Credential
Invoke-Command -ComputerName Server -ScriptBlock { snacfg workstation computer /print } -Credential $creds
Option 2:
$pwd = ConvertTo-SecureString "ThePassword" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("TheUsername", $pwd)
Invoke-Command -ComputerName Server -ScriptBlock { snacfg workstation computer /print } -Credential $creds

Powershell (Version 2.0) remote execution of services with credentials

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()};