Powershell:如何引用 select 中的列
Powershell: How to reference the columns in a select
我正在使用 PowerShell 5.1 循环访问 Active Directory 中的计算机列表,但我正在努力解决一些本应很简单的问题。
在下面的代码中,我在 foreach 循环中为每台计算机选择名称和描述。我应该如何在循环中分别引用名称和描述?
$OU=@('OU=...')
$computers = $OU | foreach {Get-ADComputer -filter {
Name -notlike 'xxx*'
-and Name -notlike 'yyy*'
} -searchbase $_ -Properties description | Select name, description }
foreach ($computer in $computers) {
$computerName = $computer | select -ExpandProperty name
$computerDescription = $computer | select -ExpandProperty description
Write-Host "Host: $computerName [$computerDescription]"
}
我能够使用 select -ExpandProperty
让它工作,但这似乎不必要地复杂。 $computer 变量包含 key/value 对,如下所示:
@{name=ABCDE12345; description=Kiosk PC [Domain Separated]}
我尝试使用圆点表示法 $computer.name $computer.description
但圆点被忽略并被视为文本。
我试过用谷歌搜索这个,但我是 PowerShell 的新手,不确定如何表达我的问题!
I tried using dot notation $computer.name $computer.description
but the dot was ignored and treated as text.
字符串扩展仅适用于简单的变量引用。如果要取消引用字符串表达式中的属性,则需要子表达式运算符 $()
:
"Host: $($computer.name) [$($computer.description)]"
PowerShell 现在将在解析字符串值时分别计算子表达式
我正在使用 PowerShell 5.1 循环访问 Active Directory 中的计算机列表,但我正在努力解决一些本应很简单的问题。
在下面的代码中,我在 foreach 循环中为每台计算机选择名称和描述。我应该如何在循环中分别引用名称和描述?
$OU=@('OU=...')
$computers = $OU | foreach {Get-ADComputer -filter {
Name -notlike 'xxx*'
-and Name -notlike 'yyy*'
} -searchbase $_ -Properties description | Select name, description }
foreach ($computer in $computers) {
$computerName = $computer | select -ExpandProperty name
$computerDescription = $computer | select -ExpandProperty description
Write-Host "Host: $computerName [$computerDescription]"
}
我能够使用 select -ExpandProperty
让它工作,但这似乎不必要地复杂。 $computer 变量包含 key/value 对,如下所示:
@{name=ABCDE12345; description=Kiosk PC [Domain Separated]}
我尝试使用圆点表示法 $computer.name $computer.description
但圆点被忽略并被视为文本。
我试过用谷歌搜索这个,但我是 PowerShell 的新手,不确定如何表达我的问题!
I tried using dot notation
$computer.name $computer.description
but the dot was ignored and treated as text.
字符串扩展仅适用于简单的变量引用。如果要取消引用字符串表达式中的属性,则需要子表达式运算符 $()
:
"Host: $($computer.name) [$($computer.description)]"
PowerShell 现在将在解析字符串值时分别计算子表达式