foreach powershell 我完全瞎了

foreach powershell i'm totally blind

我对这个 PowerShell 脚本有疑问,如果我在没有 foreach 的情况下执行该行,效果很好,但没有显示任何内容,有人可以告诉我为什么吗?

foreach 本身就很棒,他从 CSV 中读取了所有数据,但由于某种原因不起作用,CSV 包含来自我的网络的 PC 名称,如 PC1、Pc-RRHH、JosePc,就像我说的没有foreach 没问题。

    $computers = Import-Csv “C:\PowerShell\Pc.csv”

$array = @()

foreach($pc in $computers)
    {
    
    Get-WmiObject -Namespace ROOT\CIMV2 -Class Win32_Product -Computer $pc.computername 
    
    Select-Object Name, Version, PSComputerName 
    
    Where-Object -FilterScript {$_.Name -like “Adobe*”}
    
    }

此致

假设您的 CSV 文件确实有一个包含 'computername' 列的 header,您可以将代码更改为:

$computers = Import-Csv "C:\PowerShell\Pc.csv"

# let PowerShell collect the data for you in an array
$array = foreach($pc in $computers) {
    # because NameSpace 'root/CIMV2' is the default, you do not have to specify that
    Get-CimInstance -ClassName Win32_Product -ComputerName $pc.computername |
    # or use the old Get-WmiObject
    # Get-WmiObject -Class Win32_Product -Computer $pc.computername |
    Where-Object { $_.Name -like "Adobe*" } |
    Select-Object Name, Version, PSComputerName 
}

您也可以使用 -Filter 参数而不是管道到 Where-Object {..} 子句。
请注意,此过滤器需要 WQL syntax,这与 PowerShell 语法不同。

$computers = Import-Csv "C:\PowerShell\Pc.csv"

# let PowerShell collect the data for you in an array
$array = foreach($pc in $computers) {
    # because NameSpace 'root/CIMV2' is the default, you do not have to specify that
    Get-CimInstance -ClassName Win32_Product -ComputerName $pc.computername -Filter "Name like 'Adobe%'" |
    Select-Object Name, Version, PSComputerName 
}

或使用-Query参数:

$computers = Import-Csv "C:\PowerShell\Pc.csv"
# the query string to filter on. Also WQL syntax
$query = "Select * from Win32_Product where Name LIKE 'Adobe%'"

# let PowerShell collect the data for you in an array
$array = foreach($pc in $computers) {
    Get-CimInstance Get-CimInstance -Query $query -ComputerName $pc.computername |
    Select-Object Name, Version, PSComputerName 
}

根据您的评论,我了解到您的 CSV 文件根本不是 CSV,而只是一个文本文件,每个计算机名称都在单独的一行中,并且没有 header 'computername'.

在这种情况下,将 $computers = Import-Csv "C:\PowerShell\Pc.csv" 更改为 $computers = Get-Content -Path "C:\PowerShell\Pc.csv",如果 -ComputerName $pc.computername

,则在循环中使用 -ComputerName $pc