Error when calling 3rd party executable from Powershell when using an IDE

Viewed 77865

I have a PowerShell script that uses du.exe (Disk Usage originally from Sysinternals) to calculate the size of directories.

If I run du c:\Backup in the console, it works as expected, but the same line of code run in ISE or PowerGui gives the expected result plus the error

+ du <<<<  c:\backup
+ CategoryInfo          : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

Why is that? How do I avoid this error? I tried invoke-expression, using &, but no go.

Thanks for the help.

6 Answers

To avoid this you can redirect stderr to null e.g.:

du 2> $null

Essentially the console host and ISE (as well as remoting) treat the stderr stream differently. On the console host it was important for PowerShell to support applications like edit.com to work along with other applications that write colored output and errors to the screen. If the I/O stream is not redirected on console host, PowerShell gives the native EXE a console handle to write to directly. This bypasses PowerShell so PowerShell can't see that there are errors written so it can't report the error via $error or by writing to PowerShell's stderr stream.

ISE and remoting don't need to support this scenario so they do see the errors on stderr and subsequently write the error and update $error.

After pulling a load of hair out, I realised that actually, these errors only occur when running the .ps1 file from "Windows PowerShell ISE".

When I ran the same .ps1 script from a Command Line, the errors didn't happen.

powershell.exe .\MikesScript.ps1

Write this script at the top of your PowerShell script it will solve this issue and even it will not affect the whole behavior of all error commands

#prepare powershell for docker-compose commands
        if((select-string -Path $profile -Pattern "Set-Alias docker-compose 'docker-compose.cmd'") -eq $null ){
           Add-Content -Path $profile -Value "Set-Alias docker-compose 'docker-compose.cmd'"}
$str = "@echo off
        docker-compose.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 2>&1"
        if ((Get-Content "C:\Windows\System32\docker-compose.cmd" -ErrorAction Ignore) -ne $str){
            $str.Trim() | Out-File "C:\Windows\System32\docker-compose.cmd" -Encoding ascii}
Related