首页 > 解决方案 > Powrshell 导出所有 PC 的列表以及它们是否安装了特定的应用程序

问题描述

我目前使用以下 powershell 脚本将我们网络上所有虚拟机的列表及其信息导出并导出到 excel 文件中:


    #// Set CSV file name 
    $uDateTime = Get-Date -f "yyyy-MM" 
    $uCSVFile = "C:\Servers"+$uDateTime+".csv" 

    #//Export out to csv file.
    Get-ADComputer -filter * -Properties ipv4Address, OperatingSystem,DistinguishedName | 
    select-object Name, ipv4Address, OperatingSystem,  @{label='OU';expression= 
    {$_.DistinguishedName.Split(',')[1].Split('=')[1]}} |
    export-csv -path $uCSVFile

excel 内容看起来像这样:

在此处输入图像描述

我想添加另一列以指示每个服务器上是否存在特定应用程序或不喜欢这个

在此处输入图像描述

谷歌搜索后,我发现我可以利用 Get-ItemProperty 读取注册表,以检查某个程序是否安装在单个 VM 上,但我无法将代码绑定到现有的程序。根据运行此 PowerShell 脚本的机器而不是单独的每个 VM 注册表,它给了我相同的结果......

你能帮我让这个脚本读取每个虚拟机的注册表吗


    #// Set CSV file name 
    $uDateTime = Get-Date -f "yyyy-MM" 
    $uCSVFile = "C:\Servers"+$uDateTime+".csv" 

    #//Export out to csv file.
    Get-ADComputer -filter * -Properties ipv4Address, OperatingSystem,DistinguishedName | 
    select-object Name, ipv4Address, OperatingSystem,  @{label='OU';expression= 
    {$_.DistinguishedName.Split(',')[1].Split('=')[1]}},
    @{label='HelloKitty Installed';expression={(Get-ItemProperty "HKLM:\Software\HelloKitty\*" | Where { 
    $_.Version -ne $null }) -ne $null}}|
    export-csv -path $uCSVFile

标签: powershell

解决方案


要从您的目标计算机而不是当前运行脚本的计算机读取注册表项,您应该使用Invoke-Command cmdlet。
但是,请记住,它Get-ADComputer也可以列出当前离线的计算机,因此我建议使用 ForEach-Object 循环,这将使您有机会首先进行测试。

像这样的东西:

#// Set CSV file name 
$uCSVFile = 'C:\Servers{0:yyyy-MM}.csv' -f (Get-Date)

#//Export out to csv file.
$result = Get-ADComputer -Filter * -Properties ipv4Address, OperatingSystem,DistinguishedName | 
ForEach-Object {
    if (Test-Connection -ComputerName $_.Name -Count 1 -Quiet) {
        # computer is on line. If need be, add -Credential to the Invoke-Command cmdlet
        # because reading the HKEY_LOCAL_MACHINE hive needs Administrator permissions.
        # Also, the targetted machines must have the 'Remote Registry' service enabled.
        try {
            $installed = Invoke-Command -ComputerName $_.Name -ScriptBlock {
                            $null -ne (Get-ItemProperty "HKLM:\SOFTWARE\HelloKitty\*" | 
                                       Where-Object { $null -ne $_.Version }).Version
                         } -ErrorAction Stop
        }
        catch { $installed = "ERROR" }
    }
    else { $installed = "OFF-LINE" }

    # output an object
    $_ | Select-Object Name, ipv4Address, OperatingSystem,
                       @{Name = 'HelloKitty Installed'; Expression = { $installed }}
}

# now export to CSV
$result | Export-Csv -Path $uCSVFile -UseCulture -NoTypeInformation

我已将开关添加-UseCulture到 Export-Csv cmdlet,因此 csv 文件中使用的分隔符将与本地 Excel 期望的相同


推荐阅读