未显示抛出消息
Throw message not being shown
我正在尝试使用 throw
打印我自己的错误消息。考虑这个例子:
$computerName = $env:COMPUTERNAME
$adsi = [adsi]("WinNT://$computerName")
if (!($adsi.Children.Find($userGroup, 'group')))
{
throw "User group not found."
}
如果用户组不正确,将显示此错误消息:
Exception calling "Find" with "2" argument(s): The group name could not be found.
有没有办法显示我的 throw
消息,而不是一般异常?
试试这个:
$computerName = $env:COMPUTERNAME
$adsi = [adsi]("WinNT://$computerName")
try {
$adsi.Children.Find($userGroup, 'group')
}
catch{
throw "User group not found."
}
[adsi]
有抛出终止错误的习惯。 Get-ADUser
也会发生这种情况。这就是为什么需要在 try
/catch
(如 )中捕获错误。
作为替代方案,您可以通过先查询所有本地组来检查该组是否存在,然后查看您的组是否存在。
$computerName = $env:COMPUTERNAME
$adsi = [adsi]("WinNT://$computerName")
$localGroups = $adsi.children | Where-Object{$_.SchemaClassName -eq "Group"}
If($userGroup -notin $localGroups.Name){
throw "Your group is in another castle."
}
或变体
if(-not ($adsi.children | Where-Object{$_.SchemaClassName -eq "Group" -and $_.Name -eq $userGroup})){
throw "Your group is in another castle."
}
根据您在何处继续使用此代码,将此信息存储一次可能会更有利。
我正在尝试使用 throw
打印我自己的错误消息。考虑这个例子:
$computerName = $env:COMPUTERNAME
$adsi = [adsi]("WinNT://$computerName")
if (!($adsi.Children.Find($userGroup, 'group')))
{
throw "User group not found."
}
如果用户组不正确,将显示此错误消息:
Exception calling "Find" with "2" argument(s): The group name could not be found.
有没有办法显示我的 throw
消息,而不是一般异常?
试试这个:
$computerName = $env:COMPUTERNAME
$adsi = [adsi]("WinNT://$computerName")
try {
$adsi.Children.Find($userGroup, 'group')
}
catch{
throw "User group not found."
}
[adsi]
有抛出终止错误的习惯。 Get-ADUser
也会发生这种情况。这就是为什么需要在 try
/catch
(如
作为替代方案,您可以通过先查询所有本地组来检查该组是否存在,然后查看您的组是否存在。
$computerName = $env:COMPUTERNAME
$adsi = [adsi]("WinNT://$computerName")
$localGroups = $adsi.children | Where-Object{$_.SchemaClassName -eq "Group"}
If($userGroup -notin $localGroups.Name){
throw "Your group is in another castle."
}
或变体
if(-not ($adsi.children | Where-Object{$_.SchemaClassName -eq "Group" -and $_.Name -eq $userGroup})){
throw "Your group is in another castle."
}
根据您在何处继续使用此代码,将此信息存储一次可能会更有利。