0

I have the following script:

$job = Invoke-Command -ComputerName $hostname -ScriptBlock {powershell.exe -ExecutionPolicy Bypass -File $using:localScriptPath -InstallApproved} -AsJob -Credential $credentials

My variables are set elsewhere in the script.

This code successfully kicks off a PowerShell script on the remote server, however it seems as though it does not leave the script running.

As its a large SCCM update script, I need it to execute it and move on, rather than sit around and wait for it to complete as I have multiple servers - how can I do this?

I tried -AsJob and it didnt work.

1
  • To target multiple servers, pass their names as an array to -ComputerName. Describe in what way -AsJob didn't work. Note that you don't need to call your script via a powershell.exe child process. Commented Jan 12 at 20:18

1 Answer 1

2

I tried -AsJob and it didnt work.

I'm assuming this relates to prematurely terminating remote jobs - try doing the other stuff you need to do, then call Wait-Job to ensure the remote job finished before you exited the script:

$localScriptPath = "C:\some\path\to\a\script.ps1"
foreach ($hostname in $hostnames) {
  # kick off remote payload as job
  $job = Invoke-Command -ComputerName $hostname -ScriptBlock {
    & $using:localScriptPath -InstallApproved 
  } -AsJob -Credential $credentials

  # simulating "other stuff"
  Start-Sleep -Seconds 5

  # wait for job to finish
  $job |Wait-Job

  # optionally do post-remote-script stuff here
}

As suggested in the comments, there's no need to call powershell.exe on the remote side - you're already running in a remote PowerShell session!

If you need to target multiple machines up front and don't care about synchronization with the rest of the script, kick off all remoting jobs at once by passing multiple hostnames to Invoke-Command -ComputerName:

$localScriptPath = "C:\some\path\to\a\script.ps1"
# kick off all the remoting jobs at once
$jobs = Invoke-Command -ComputerName $hostname -ScriptBlock {
  & $using:localScriptPath -InstallApproved 
} -AsJob -Credential $credentials

foreach ($hostname in $hostnames) {
  # simulating "other stuff"
  Start-Sleep -Seconds 5
}

$jobs |Wait-Job -TimeOut 60 # optionally time out after X seconds of waiting (here 60 seconds)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.