throw关键字可以生成 ErrorRecord 对象。ErrorRecord 对象的 Exception 属性包含 RuntimeException 对象。ErrorRecord 对象和 RuntimeException 对象的其余部分因被引发的对象而异。 throw对象包装在 ErrorRecord 对象中,ErrorRecord 对象自动保存在$Error自动变量中。
PowerShell 复制 function Start-Something { [CmdletBinding()] param() process { try { ... } catch { $PSCmdlet.ThrowTerminatingError($PSItem) } } } 由于所有内容都位于其函数内的 try 语句中,因此所有内容的行为一致。 这还会向最终用户提供简洁的错误信息,对生成的错误隐藏内部代码。
Remove-AzAks, Import-AzAksCreden... ... Script 4.4.0 Pester Desk {Describe, Context, It, Should...} Script 1.18.0 PSScriptAnalyzer Desk {Get-ScriptAnalyzerRule, Invoke-ScriptAnalyzer, Invoke-... Script 1.0.0 WindowsCompatibility Core {Initialize-WinSession, Add-WinFunction, Invok...
对象的类型为 ErrorRecord。 PowerShell 复制 try { NonsenseString } catch { Write-Host "An error occurred:" Write-Host $_ } 运行此脚本会产生以下结果: Output 复制 An Error occurred: The term 'NonsenseString' is not recognized as the name of a cmdlet, function, script file,...
param($ComputerName= $(throw"ComputerName parameter is required."))functionCanPing {$Error.Clear()$tmp=Test-Connection$ComputerName-ErrorActionSilentlyContinueif(!$?) {Write-Host"Ping failed:$ComputerName.";return$false}else{Write-Host"Ping succeeded:$ComputerName";return$true} }functionCanRemote...
if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue") { throw "SQL Server Provider for Windows PowerShell is not installed." } else { $item = Get-ItemProperty $sqlpsreg $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path) ...
+ FullyQualifiedErrorId : Date required可以在定义函数时跳过参数声明,而在函数体中声明。函数体本身以脚本块的形式存在,可以包含param语句。下例中的Format-Date函数在脚本块中声明变量:展开表 PS C:\PowerShell> function Format-Date >> { >> param ($date = $(throw "Date required"), $format = "...
if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue") { throw "SQL Server Provider for Windows PowerShell is not installed." } else { $item = Get-ItemProperty $sqlpsreg $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path) ...
For further information regarding how a cmdlet should determine when to throw a terminating error or non-terminating error, MSDN has a nice explanation here. Update 12/13/2013: Want to know if an error you encountered is terminating or non-terminating? Check to see if the error behavior is ...
# This does not throw an error, but is not guaranteed to work since the dictionary object is not thread safe $threadUnSafeDictionary = [System.Collections.Generic.Dictionary[string,object]]::new() Get-Process | ForEach-Object -Parallel { $dict = $using:threadUnSafeDictionary $dict.TryAdd($...