$ LASTEXITCODE严格用于命令行程序返回其状态。内置于PS中的Cmdlet(如Remove-item)最多以3种方式返回错误。对于警告,他们将消息(或其他.NET对象)写入“警告流”。在PSv3中,可以直接将该流重定向到文件:cmdlet blah blah blah 3>warning.out
。第二个是通过错误流。该流也可以重定向... 2>error.out
,或者更常见的错误是使用try/catch或trap捕获的,或者通过-ErrorVariable参数写入变量(请参阅help about_commonparameters
)。第三种方式是错误被“抛出”。除非被捕获(try/catch或trap),抛出的错误将导致脚本终止。抛出的错误通常是.NET类system.Management.Automation.ErrorRecord
的子类。 ErrorRecord提供了比错误代码更多的关于错误的信息。
如果remove-item因文件未找到错误而失败,它会向错误流写入System.Management.Automation.ItemNotFoundException
。使用try/catch可以筛选特定错误或remove-item中的其他特定错误。如果您只是从命令行输入PS命令,则可以输入$error[0]|select-object *
以获取关于上次错误的大量信息。
你可以这样做:
try {
Remove-Item -Recurse -Force C:\users\bkp 2>&1
} catch {
# oops remove-item failed. Write warning then quit
# replace the following with what you want to do
write-warning "Remove-item encounter error: $_"
return # script failed
}
您可以只检查$ error变量。这包含了会话中遇到的每一个错误,并且我认为它确实对内存分配有限制。 –