windows – 如何在PowerShell中捕获异常?
发布时间:2020-12-14 01:53:35 所属栏目:Windows 来源:网络整理
导读:如果我有一段抛出异常的代码,我会得到一条错误消息,但我不知道如何正确捕获(或确定)抛出的异常.通常我会抓住System.Exception,这是一个坏主意. 这是一个例子……我正在尝试在不存在的驱动器上创建一个文件夹: PS dir .myScript.ps1 z:testmkdir : Cannot
如果我有一段抛出异常的代码,我会得到一条错误消息,但我不知道如何正确捕获(或确定)抛出的异常.通常我会抓住System.Exception,这是一个坏主意.
这是一个例子……我正在尝试在不存在的驱动器上创建一个文件夹: PS <dir> .myScript.ps1 z:test mkdir : Cannot find drive. A drive with the name 'z' does not exist. At <dir>myScript.ps1:218 char:7 + mkdir $args[0] 1> $null + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (z:String) [New-Item],DriveNotFoundExc eption + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemComm and 我已经尝试捕获System.DriveNotFoundException,但重新运行我的脚本仍然会产生未捕获的异常. 有效处理任何类型的例外是否有任何提示? 解决方法
运行命令后立即检查$error [0]的内容.看看Exception属性,例如:
$error[0] | fl * -force writeErrorStream : True PSMessageDetails : Exception : System.Management.Automation.DriveNotFoundException: Cannot find drive. A drive with the name 'z' does not exist. at System.Management.Automation.SessionStateInternal.GetDrive(String name,Boolean automount) at System.Management.Automation.SessionStateInternal.GetDrive(String name,Boolean 那个特殊的例外是[System.Management.Automation.DriveNotFoundException]. 顺便说一句,如果你想“捕获”那个异常,你需要使用-EA Stop将非终止错误转换为终止错误,以便它生成一个你可以捕获的异常,例如: PS> try {mkdir z:foo -ea Stop} catch {$_.Exception.GetType().FUllname} System.Management.Automation.DriveNotFoundException (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- windows – 用于连接到无线网络的命令行实用程序
- 在Windows上并行写入Java
- windows-phone-7 – vmouse事件的问题WP7 JQueryMobile
- windows-server-2008 – TrustedInstaller.exe需要大量的CP
- 适用于Windows的Phantomjs安装
- windows-phone-7 – Twitter,OAuth,Hammock,TweetSharp和Wi
- 删除流氓软件小黑记事本流氓代码HNShell64.dll
- windows-8 – WinRT HttpClient阻止闪屏
- .net – Windows工作流 – PersistableIdle
- 纠正整个Windows域中的时间偏差