首页 > 解决方案 > 从多台远程计算机卸载程序并生成报告

问题描述

问题 1:我在下面有一个脚本,它将卸载本地主机上的程序,但在输出中我只需要主机名和卸载状态

$app = Get-WmiObject -Class Win32_Product -Filter "Name = 'Test'"

$app.Uninstall() 

问题 2:我在下面有一个脚本,它在多台远程机器上运行,它正在做的事情,但有时输出文件的结果是错误的。我需要一个包含主机名和卸载状态列的文件的输出

$computers = (Get-Content 'C:\Test\testmchines.txt')

foreach ( $computer in $computers ) {

    $Test = Get-WMIObject -Class Win32_Product -Filter "Name Like '%Test%'" -ComputerName $computer

    if ($Test) {
        "Found {0} on {1}" -f $Test.Name, $computer

        $result = $Test.Uninstall()
        if ($result -eq 0) {
            "Uninstall successful on {0}" -f $computer | out-file 'C:\Test\uninstall.txt' -Append
        }
        else {
            "Uninstall failed on {0}" -f $computer | out-file 'C:\Test\uninstall.txt' -Append
        }
    }
    else {
        "Test is not found on {0}" -f $computer | out-file 'C:\Test\uninstall.txt' -Append
    } }

请在上述脚本中建议更正以获得所需的输出。

所需输出:包含主机名和卸载状态、未找到测试应用程序列的报告/文件

标签: powershellpowershell-3.0powershell-4.0powershell-remoting

解决方案


出于报告目的,您可以使用CSV格式化文件。创建一个包含所需信息的对象,并使用Export-Csvcmdlet 将数据导出到文件。我稍微更改了您的脚本,以向您展示根据过程条件创建和设置其属性的对象。

我希望你明白了。

$computers = @(Get-Content 'C:\Test\testmchines.txt')

foreach ($computer in $computers){
    $Obj = New-Object PSCustomObject -Property @{ComputerName=$computer;TestExists=$false;Uninstalled=$false}

    $Test = Get-WMIObject -Class Win32_Product -Filter "Name Like '%Test%'" -ComputerName $computer

    if ($Test){
        $Obj.TestExists = $true
        $result = $Test.Uninstall()
        if ($result -eq 0) {
            $Obj.Uninstalled = $true
        }
    }
    $Obj | Export-Csv -Path 'C:\Test\uninstall.txt' -Append -NoTypeInformation
}

推荐阅读