PowerShell 中 $error 变量有什么作用?


PowerShell 中的 Error 变量用于查看当前 PowerShell 会话中生成的错误。我们可以说 $Error 变量是存储所有错误的容器,最新的错误将首先显示。对于下面的示例,我们将 $ErrorView 设置为 Category 视图以最小化错误显示内容。默认情况下,$ErrorViewNormal 视图

$ErrorView = "Categoryview"

现在我们将看到 $error 变量的示例,

PS C:\WINDOWS\system32> asdds
ObjectNotFound: (asdds:String) [], CommandNotFoundException
PS C:\WINDOWS\system32> Get-process asddsd
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException

这里,我们编写了一个错误的命令和一个错误的输入,所以让我们看看 $error 变量包含什么。

PS C:\WINDOWS\system32> $error
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException

在上面的输出中,最后一个错误将首先显示,依此类推。$Error 变量现在已成为一个数组。您可以像使用普通数组一样获取各个输出。

PS C:\WINDOWS\system32> $error[0]
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
PS C:\WINDOWS\system32> $error[1] ObjectNotFound: (asdds:String) [], CommandNotFoundException

要获取生成的错误数量,

PS C:\WINDOWS\system32> $error.Count
2

要检查错误容量,您可以运行以下命令。

PS C:\WINDOWS\system32> $error.Capacity
4

当存储错误的容量达到 4 时,此变量会自动将其容量再次增加 4,因此总容量变为 8。因此,每次错误变量达到其容量时,它都会将其容量增加 4。

例如,

我们在这里已经创建了 4 个错误,

PS C:\WINDOWS\system32> $error
ObjectNotFound: (221dsd:String) [], CommandNotFoundException
ObjectNotFound: (7sdse:String) [], CommandNotFoundException
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException

当您再添加一个错误计数时,

PS C:\WINDOWS\system32> 5look
ObjectNotFound: (5look:String) [], CommandNotFoundException

现在检查容量,

PS C:\WINDOWS\system32> $error.Capacity
8

以及输出,

PS C:\WINDOWS\system32> $error
ObjectNotFound: (5look:String) [], CommandNotFoundException
ObjectNotFound: (221dsd:String) [], CommandNotFoundException
ObjectNotFound: (7sdse:String) [], CommandNotFoundException
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException

所以问题是,这个错误变量容量的阈值是多少?要检查它,您需要使用命令 $MaximumErrorCount

PS C:\WINDOWS\system32> $MaximumErrorCount
256

这里,最大错误计数的限制为 256

更新于: 2020-05-27

3K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.