So I have some code that allows me to open a remote session via PSSession and execute some code in a scriptblock. I can pass local variables to the scriptblock for use in the remote execution via "-Args". That works great. But now I need to retrieve a variable that is created in the scriptblock on the remote host so I can check it's value locally. Sample code below:
I can't seem to get the $Exitcode value to work. I have very similar code that works great as a local function. If I leave the PSSession open after the script completes, I can "Enter-PSSession $RemoteSession" and check the value of $Exitcode, and it has the correct data there. So I know that it is getting set in the remote session to the correct exit code value for the .EXE command that it runs. I just need to get that value back from the remote host somehow.
________________________________________
CompTIA A+, Network+, Server+, Security+
MCTS:Windows 7
MCSE:Security 2003
MCITP:Server Administrator
MCITP:Enterprise Administrator
MCITP:Virtualization Administrator 2008 R2
Certified Quest vWorkspace Administrator
Code:
$RemoteHost = "server.fqdn.com"
# This function calls external executables, waits for them to complete and returns the exit code
function Run-RemoteProcess ($cmd, $Parameters) {
$RemoteSession = New-PSSession -ComputerName $Remotehost
#Enter-PSSession -session $RemoteSession
Invoke-Command -Session $RemoteSession -Scriptblock {param($cmd,$Parameters)
$Process = New-Object System.Diagnostics.Process;
$Process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo;
$ExitCode = $false;
$Process.StartInfo.FileName = $cmd;
$Process.StartInfo.Arguments = $Parameters;
$Process.StartInfo.UseShellExecute = $shell;
$Process.StartInfo.WindowStyle = 1;
$null = $Process.Start();
$Process.WaitForExit();
$Global:ExitCode = $Process.ExitCode;
$Process.Dispose();
} -Args $cmd,$Parameters
#Exit-PSSession
#Remove-PSSession $RemoteSession
If ($Process.ExitCode -ne 0) {
#Log an error
#Sets performance counter State to Warning
#$PerfCounterState = new-object
}
Else {
#Logs success
}
#$PerfCounterData.Increment()
return $ExitCode
}
"Returncode = " + $Returncode
$ReturnCode = Run-RemoteProcess ping.exe "-n 10 192.168.199.199"
I can't seem to get the $Exitcode value to work. I have very similar code that works great as a local function. If I leave the PSSession open after the script completes, I can "Enter-PSSession $RemoteSession" and check the value of $Exitcode, and it has the correct data there. So I know that it is getting set in the remote session to the correct exit code value for the .EXE command that it runs. I just need to get that value back from the remote host somehow.
________________________________________
CompTIA A+, Network+, Server+, Security+
MCTS:Windows 7
MCSE:Security 2003
MCITP:Server Administrator
MCITP:Enterprise Administrator
MCITP:Virtualization Administrator 2008 R2
Certified Quest vWorkspace Administrator