我正在尝试遍历计算机列表并检索每台计算机的模型。当我使用Write-Output打印每台计算机的名称时,这正是我所期望的(只是名称)。但是,当我尝试使用wmic命令获取模型时,似乎正在使用“ CN = $ name”。并且即使我执行了.Substring(3),它仍然会抛出错误“找不到别名”,并显示“ CN = $ name”。这是我的脚本:
$computers = Get-ADComputer -Filter '*'
foreach ($computer in $computers) {
Write-Output $computer.Name # Outputs how I expect, just the name
wmic /node:$computer.Name csproduct get name | Write-Output # Throws error, alias not found CN=$name
}
执行此操作时:
wmic /node:$computer.Name csproduct get name
PowerShell仅认为$computer
是应扩展的变量。因此,它将在ToString()
上执行一个$computer
,这是计算机的完整专有名称。如果输出以下内容,则可以看到此内容:
Write-Output "$_.Name"
您会看到获得的专有名称后面附加有.Name
。
为了避免这种情况,您可以通过将其包含在$_.Name
中来明确告诉它要解析$( )
:
wmic /node:$($computer.Name) csproduct get name
如果您愿意,可以在这里阅读有关此内容的更多信息:Variable expansion in strings and here-strings