If I pass an IF statement through PowerShell's Invoke-Expression
, the command appears to be running and completing, but then it appears that the output is being evaluated as a new command instead of being returned to PowerShell. Three examples:
Invoke-Expression 'echo "hi"'
(No IF statement)
Normal Output: hi
Invoke-Expression 'cmd /c IF exist C:\Windows (echo "hi")'
Error on Output: 'hi' is not recognized as an internal or external command, operable program or batch file.
Invoke-Expression 'cmd /c IF exist C:\Windows (query user)'
Error on Output:
'" USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME"' is not recognized as an internal or external command, operable program or batch file.
What's the best way to run a command-line IF statement from PowerShell and be able to read its output? I tried Start-Process
but cannot figure out for the life of me how to read its output. Tried a System.Diagnostics.ProcessStartInfo
object copied from another StackOverflow post, but no luck there either.
Because people are bound to ask: The reason why I'm passing this through cmd in the first place is because this entire code block needs to be passed through Invoke-Command
to a remote machine and cmd has folder/file access to computers on its network while PowerShell does not.