我尝试将成员“ canonicalName”添加到对象。当我使用声明时:
$obj | Add-Member NoteProperty "CanonicalName"
-value (Get-ADComputer $row.ServerName -Properties CanonicalName).CanonicalName
“ canonicalName”列根本没有出现。 将语句与变量一起使用:
$a = (Get-ADComputer $row.ServerName -Properties CanonicalName).CanonicalName
$obj | Add-Member NoteProperty "CanonicalName" -value $a
works perfectly.
提示:我正在遍历的某些ServerName在域中不再存在。 代码:
$data = $dataSet.Tables[0]
$ErrorActionPreference = "silentlycontinue"
$info = @()
foreach($row in $data)
{
$obj = New-Object psobject
$obj | Add-Member NoteProperty "ServerName" -Value $row.ServerName
#$a = (Get-ADComputer $row.ServerName -Properties CanonicalName).CanonicalName
#$obj | Add-Member NoteProperty "CanonicalName" -value $a
$obj | Add-Member NoteProperty "CanonicalName" -value (Get-ADComputer $row.ServerName -Properties CanonicalName).CanonicalName
$info += $obj
}
$info | ft -AutoSize
我希望得到:
ServerName CanonicalName
---------- -------------
N3751022 xx.yy.de/Memberserver/SQL-Cluster/xx/n3887022
N3732022 xx.zz.de/Memberserver/yy/uu/zz/N3732022
在没有变量$ a的情况下,我得到的全部是(没有列canonicalName):
ServerName
----------
N3751022
N3732022
我已经在不同的域中测试了代码(数据集中的所有服务器都在域中!),即使没有canonicalName的值,我也会得到正确的结果(两列serverName和canonicalName)。给定的serverName。
答案 0 :(得分:1)
使用try / catch可能是您的解决方法...
但是请注意,此示例中使用的catch块很不精确。运行Get-ADComputer的任何异常都将被视为相同,我们只是假设Get-ADComputer没有输出表示该计算机不是域的成员。
$data = $dataSet.Tables[0]
$ErrorActionPreference = "silentlycontinue"
$info = @()
foreach($row in $data)
{
$obj = New-Object psobject
$obj | Add-Member NoteProperty "ServerName" -Value $row.ServerName
try {
$obj | Add-Member NoteProperty "CanonicalName" -Value (Get-ADComputer $row.ServerName -Properties CanonicalName).CanonicalName
} catch {
$obj | Add-Member NoteProperty "CanonicalName" -Value $null
}
$info += $obj
}
$info | ft -AutoSize
答案 1 :(得分:0)
这就是我要做的。如果没有匹配的记录而不是错误,那么在Get-ADComputer
上使用过滤器将使其返回null:
$data = $dataSet.Tables[0]
$ErrorActionPreference = "silentlycontinue"
$info = @()
foreach ($Row in $Data) {
$ServerName = $Row.ServerName
$obj = New-Object psobject
$obj | Add-Member NoteProperty "ServerName" -Value $ServerName
$CanonicalName = (Get-ADComputer -Filter {Name -like $ServerName} -Properties CanonicalName).CanonicalName
if ($CanonicalName) {
$obj | Add-Member NoteProperty "CanonicalName" -value $CanonicalName
}
else {
$obj | Add-Member NoteProperty "CanonicalName" -value $null
}
$info += $obj
}
$info | ft -AutoSize