powershell - 从多台远程计算机卸载程序并生成报告
问题描述
问题 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
} }
请在上述脚本中建议更正以获得所需的输出。
所需输出:包含主机名和卸载状态、未找到测试应用程序列的报告/文件
解决方案
出于报告目的,您可以使用CSV
格式化文件。创建一个包含所需信息的对象,并使用Export-Csv
cmdlet 将数据导出到文件。我稍微更改了您的脚本,以向您展示根据过程条件创建和设置其属性的对象。
我希望你明白了。
$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
}
推荐阅读
- c - 当我尝试更改数组的值并且如果我在没有 malloc 的情况下声明数组时会出现 Seg 错误
- django - Django - 如何摆脱多次保存
- google-apps-script - 在单元格中设置公式时,谷歌应用程序脚本出错
- python - 如何在散景中使用“点击”来影响不同情节(或表格)的变化?
- c# - 有没有办法将字节数组转换为十六进制字符串?
- azure - 使用 azure iot hub 连接到现有 OPC
- racket - 如何将 xexpr 表达式分解为 Racket 中的函数?
- javascript - 按出现字符拆分字符串
- r - 如何使用 tidyr/dplyr 对数据框的元素进行分组和选择
- php - 后端文件数组结构错误