使用以下方法/语法在for循环内创建/清除/初始化对象的正确方法是什么?使用此方法可以提高性能。
$objComputer = [pscustomobject] @{}
我注意到,如果AD中不存在其中一个系统并返回错误或null,则会在数组中使用上一个条目/对象中的信息。例如,计算机03有效,但BLAH(不是)从计算机03的上一个条目中拉出。
function Get-ADComputers ($NameList) {
$arrayComputer = @();
foreach ($line in $NameList.Split("`r`n") | ? { $_ }) {
$PCName = $line.Trim()
$Computer = (Get-ADComputer -Identity $PCName -Properties *)
$objComputer = [pscustomobject] @{
Computer = $PCName
Active = $Computer.Enabled
Date = $Computer.PasswordLastSet
DaysOld = (Get-DaysOld $Computer.PasswordLastSet)
OU = $Computer.DistinguishedName
}
write-host $objComputer
$arrayComputer += $objComputer
$objComputer = $null;
} return $arrayComputer
}
结果
Computer Active Date DaysOld
Computer-01 TRUE 4/12/2015 8:16 -29
Computer-02 TRUE 5/4/2015 7:11 -7
Computer-03 TRUE 4/20/2015 9:01 -21
BLAH TRUE 4/20/2015 9:01 -21
Computer-03 TRUE 4/6/2015 8:14 -35
Computer-04 TRUE 5/9/2015 17:17 -1
Computer-05 TRUE 4/17/2015 12:04 -24
感谢您的帮助! :)
使用TRY CATCH编辑示例:
function Get-ADComputers ($NameList) {
$arrayComputer = @();
foreach ($line in $NameList.Split("`r`n") | ? { $_ }) {
$Computer = $null
$PCName = $line.Trim()
try {
$Computer = (Get-ADComputer -Identity $PCName -Properties *)
$objComputer = [pscustomobject] @{
Computer = $PCName
Active = $Computer.Enabled
Date = $Computer.PasswordLastSet
DaysOld = (Get-DaysOld $Computer.PasswordLastSet)
OU = $Computer.DistinguishedName
}
} catch {
$objComputer = [pscustomobject] @{
Computer = "$PCName"
Active = "Missing"
Date = "N/A"
DaysOld = "N/A"
OU = "N/A"
}
}
write-host $objComputer
$arrayComputer += $objComputer
$objComputer = $null;
} return $arrayComputer
}
答案 0 :(得分:3)
如果对Get-ADComputer
的调用失败,则$Computer
不会被清除。您需要以某种方式处理错误。一个简单的解决方案:
$Computer = $null
$Computer = (Get-ADComputer -Identity $PCName -Properties *)
if(!$Computer) { #handle a missing computer
$objComputer = [pscustomobject] @{
Computer = "Computer not found"
Active = "FALSE"
Date = "N/A"
DaysOld = "N/A"
OU = "N/A"
}
}
您还可以使用try / catch块。如果你不在乎这么多,你可以使用-ErrorAction SilentlyContinue
。