Douglas Woods
Douglas Woods

Reputation: 964

Powershell with -noexit does not write errors to stderr

If I have a powershell script the causes an error, I cannot get the error written to stderr if I use -noexit

For example if I have the following script foo.ps1

Get-Process none

If run this without -noexit the error is written to stderr

PS E:\Play>powershell -file .\foo.ps1 2>Error1.txt

If I use the -noexit param the error is not written to stderr

PS E:\Play>powershell -noexit -file .\foo.ps1 2>Error2.txt

What do I have to do to get the error written to stderr when using -noexit?

Upvotes: 1

Views: 77

Answers (1)

JosefZ
JosefZ

Reputation: 30123

Why do you run powershell from PowerShell prompt? Just use

PS E:\Play>.\foo.ps1 2>Error1.txt

or (see Understanding Streams, Redirection, and Write-Host in PowerShell)

PS E:\Play>.\foo.ps1 *>&1 | Tee-Object -FilePath Error1.txt

To run above statements from cmd.exe command prompt, you need to escape some characters to be survived into the powershell (note all ^ carets):

E:\Play>powershell .\foo.ps1 2^>Error1.txt

or

E:\Play>powershell .\foo.ps1 *^>^&1 ^| Tee-Object -FilePath Error1.txt

Omit -file switch and use e.g. -NoExit from command prompt, see powershell /?.

Upvotes: 1

Related Questions