Search code examples
powershellpowershell-remotingpsexecinvoke-command

Is return code required for Invoke-Command


Powershell script

  1. Enables PSRemoting on a remote computer
  2. Executes setup.exe on a remote computer
  3. Disables PSRemoting on a remote computer

How can I be sure that I am disabling PSRemoting after the remote computer is able to execute setup.exe?

Am I disabling PSRemoting before the remote computer is able to execute setup.exe?

$password = get-content D:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "Administrator",$password
$j = "remote_computer"

$comp = "\\"+$j

$exe = "setup.exe"
[String]$cmd = "cmd /c 'C:\share\$exe'"
[ScriptBlock]$sb = [ScriptBlock]::Create($cmd) 


$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$str =  [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)



$enable_command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $str -accepteula powershell.exe c:\share\ps_enable.ps1"

Invoke-Expression $enable_command


try{
    invoke-command -ComputerName $j -Credential $credentials -ScriptBlock $sb

}
catch [System.Exception]{
    continue
}


$disable_command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $str -accepteula powershell.exe c:\share\ps_disable.ps1"

Invoke-Expression $disable_command

Solution

  • Easy enough, use the AsJob switch for Invoke-Command and assign it to a variable. Then use Wait-Job so that you know that the job completed before you move on to disabling PSRemoting.

    try{
        $SetupJob = invoke-command -ComputerName $j -Credential $credentials -ScriptBlock $sb -AsJob
    
    }
    catch [System.Exception]{
        continue
    }
    
    $SetupJob|Wait-Job
    
    $disable_command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $str -accepteula powershell.exe c:\share\ps_disable.ps1"
    
    Invoke-Expression $disable_command