Try Catch在函数/函数中不工作



两个函数一个调用另一个

当我离开$path参数或$ComputerName参数NULL时,函数Export-LoggedOnUser中的CATCH块不会被触发。Export-LoggedOnUser函数正在调用第一个函数get - loggedonuser。如果我让$ComputerName参数为空,它也不会触发catch块。我用不同的方式编写了这些函数,除了TRY/CATCH结构在两个函数中都不能执行外,它们都能按预期工作。

典型的错误是一些总是'ParameterBindingValidationException'的一些变化,这是预期的,除了它没有在CATCH中处理。我的困惑。必须是简单的

function Get-LoggedOnUser{
[CmdletBinding()]
[Alias()]
Param
(
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateScript({Test-Connection -ComputerName $_ -Quiet -Count 1})]
[ValidateNotNullOrEmpty()]
[string[]]$ComputerName 
)
Try{
ForEach($computer in $ComputerName){
$output = @{
'ComputerName' = $computer;     }#OutputHashTable
$output.UserName = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer -ErrorAction Stop).Username    
[PSCustomObject]$output
}
}
Catch{
Write-host 'You must enter a valid computername'
}
}
#New Function
function Export-LoggedOnUser{
[CmdletBinding()]
[Alias()]
Param(
[Parameter(Mandatory=$True)]
[string]$Path,
[Parameter(Mandatory=$True)]
[string[]]$ComputerName
)
try{
$loggedonuser = Get-LoggedOnUser -ComputerName $ComputerName -ErrorAction stop 

}
catch{
Write-Host "You need to provide a Computername"
}
Try{
$loggedonuser | Export-Csv -Path $Path -NoTypeInformation -ErrorAction Stop
}
Catch{
Write-Host 'You must enter a valid path'
} 
}

Christian,

如果您想测试$Computername参数并提供错误消息,我将删除参数验证并执行以下操作:

Function Test {
Param (
[Parameter(Mandatory=$False)]
[String[]] $ComputerName
)
If ($Null -ne $ComputerName) {
ForEach ($Computer in $ComputerName) {
$GCIMArgs = @{Class        = 'Win32_ComputerSystem'
ComputerName = "$computer"
ErrorAction  =  'Stop'}
Try   { $UserName = (Get-CIMInstance @GCIMArgs ).Username }
Catch { "Error: $Computer is an invalid computer name!"   }
<#+-----------------------------------------------------------+
| Place your code her to place $username in your PSObject!  |
+-----------------------------------------------------------+
#>
} #End ForEach
} #End If ($Null -ne $ComputerName)
Else { "You must supply a valid array of computer names..." }
} #End Function Test
#--------------------  Main Program ---------------------
Test @("DellXPS8920","Dellxps8700","JanetsLaptop")

如果按上面所示运行,您将得到如下输出:

Error: JanetsLaptop is an invalid computer name!

这对我的局域网是正确的,因为笔记本电脑没有打开。

如果你只调用TEST数组,你会得到这个:

You must supply a valid array of computer names...

最新更新