1

PowerShell snippet:

Import-Module Pscx
Expand-Archive ConsoleApplication1.zip ./
Write-Host $?
Write-Host $LastExitCode

Neither $? nor $LastExitCode report about error. But there is error, because file ConsoleApplication1.exe is locked (i started this app). I can see failure by following output:

WARNING: ArchiveCallBack->GetStream error: System.IO.IOException:
The process cannot access the file 'D:\tmp\ConsoleApplication1.exe'
 because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
...

Question: how can I detect in powershell that Expand-Archive failed

Thanks

Roman
  • 4,531
  • 10
  • 40
  • 69

2 Answers2

3

Looks like I've found solution that works:

$w = $null
Expand-Archive ConsoleApplication1.zip ./ -WarningVariable w

If error occurs (or call them warnings) they are collected in $w variable. If $w.Count -gt 0 it means some error/warning have occured.

Roman
  • 4,531
  • 10
  • 40
  • 69
  • Nice workaround - please submit an issue on pscx.codeplex.com anyway... thanks! – x0n Feb 10 '11 at 18:21
1

$LastExitCode is purely for native EXE exit codes. It doesn't apply to cmdlets. $? should work if the cmdlet detects that it has errored and writes out an error object. It appears this cmdlet isn't internally detecting the error. If you run $error.Clear(), then the Expand-Archive command, does $error[0] contain an error?

Also, is it possible that the cmdlet is still expanding the exe when you try to execute it? I assume you're waiting for the cmdlet to finish before attempting to execute the console app. I guess it's also possible there's a bug where the file is being closed/disposed. What if you try a [gc]::collect() after the Expand-Archive. Do you still get the error?

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • `$errors.Count` remains the same. With console app - it is only an example how to make `Expand-Archive` cmd-let fail. The main idea was to somehow lock the file – Roman Feb 10 '11 at 06:11
  • In that case, Expand-Archive doesn't think it failed so using $? is a no go. – Keith Hill Feb 10 '11 at 15:31
  • 3
    My bad - I really should be writing a non-termating error instead of a warning record. – x0n Feb 10 '11 at 18:20