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)
-ComputerName. Describe in what way-AsJobdidn't work. Note that you don't need to call your script via apowershell.exechild process.