Error calling third-party executable from Powershell when using IDE

I have a PowerShell script that uses du.exe ( Using Disk 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 running in ISE or PowerGui gives the expected result plus an error

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

Why? How to avoid this error? I tried calling the expression using & , but don't leave.

Thanks for the help.

+43
powershell ide powergui du
Jan 19
source share
5 answers

To avoid this, you can redirect stderr to zero, for example:

 du 2> $null 

In essence, the console host and ISE (as well as remote access) handle the stderr stream differently. On the console host, it is important that PowerShell supports applications such as edit.com to work with other applications that write color output and errors on the screen. If the I / O stream is not redirected to the console host, PowerShell provides its own console console descriptor for writing directly. This bypasses PowerShell, so PowerShell does not see that there are errors, so it cannot report the error using the $ error or writing to the PowerShell stderr stream.

ISE and remote access do not need support for this scenario, so they see errors in stderr and then write the error and update $ error.

+32
Jan 19 '10 at 17:45
source share

I recently ran into the same problems, but I would like to get stderr output intended for stdout. You might think the following would work:

  & du 2>&1 

But PowerShell will interpret the redirection and process it after the completion of 'du'. The workaround I found is to call it with cmd.exe / c:

  & cmd /c 'du 2>&1' 
+29
May 2 '13 at 9:08
source share

Another way to suppress the output of a NativeCommandError is to convert the objects in the pipeline to strings, as this answer describes below:

 du c:\Backup 2>&1 | %{ "$_" } 
+6
Jan 06
source share

Try:

 du 2>&1 | %{ "$_" } 
+2
Oct. 20 '16 at 8:56
source share

The previous FIX will redirect errors, but you can lose a real error if, for example, your username or password does not match or if you use integrated authentication, you do not have access.

So, here is a way to implement error handling and work around a specific error (i.e. not one) caused by psexec.

  try{ psexec command ..... } catch [System.Management.Automation.RemoteException]{ if ($_.TargetObject -like "Connecting to *" -and $_.CategoryInfo.Category -eq "NotSpecified" -and $_.FullyQualifiedErrorId -eq "NativeCommandError" -and $_.InvocationInfo.MyCommand.Name -like "psexec*.exe"){ $error.Remove[$Error[0]] } else{ Throw } } catch{ throw } 
0
Feb 17 '17 at 20:30
source share



All Articles