I am trying to run a script remotely that will double check that the IP address is correct using PsExec in Powershell. The problem is I only want it to return the result True or False and not show any other lines within Powershell.
I have tried running background jobs as well but have not seemed to get that working, as when I do that it simply gives me nothing.
function remoteIPTest($Computer) {
$result = & cmd /c PsExec64.exe \\$Computer -s cmd /c "ipconfig"
if ($result -like "*10.218.5.202*") {
return "True"
}
}
$Computer = "MUC-1800035974"
remoteIPTest $Computer
After running this, I just want the application to give return:
True
Instead of returning:
Starting cmd on MUC-1800035974... MUC-1800035974...
cmd exited on MUC-1800035974 with error code 0.
True
psexec
prints its status messages to stderr, which a variable assignment such as $result =
does not capture, so these messages still print to the screen.
Variable assignments only capture stdout output from external programs such as psexec
, which in this case is ipconfig
's output.
Therefore, the answer is to suppress stderr, which you can do with 2>$null
(2
is the number of PowerShell's error stream, which stderr maps to) - see Redirecting Error/Output to NULL.
Do note that this will also suppress true error messages.
In addition, the cmd /c
calls are not needed, because you can use psexec
to invoke other programs directly, if you have the path configured properly.
Instead of this:
$result = & cmd /c PsExec64.exe \\$Computer -s cmd /c "ipconfig"
Do This:
$result = PsExec64.exe \\$Computer -s ipconfig 2>$null
Hope it helps.