格式化卸载程序的输出 - Powershell

时间:2017-03-14 18:23:40

标签: powershell

我想为每个"卸载"检索Publisher,DisplayName和DisplayVersion。程序并将它们放在一个文件中,每个产品一行,每个条目之间用逗号表示:

Publisher, DisplayName, DisplayVersion

我需要维护每个条目的全部内容(即不截断,如Format-Table那样)。

我将每个所需的项目放入一个数组中,以便稍后访问。

$Publisher = Get-ItemProperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Select Publisher

$DisplayName = Get-ItemProperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Select DisplayName

$DisplayVersion = Get-ItemProperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Select DisplayVersion

这样我就可以遍历这些条目,并将它们写出来。

for ($i=0; $i -lt $DisplayName.Count; $i++)
{
    $MyOutput = ( ([string]::Concat($Publisher[$i].getValue, ",", $DisplayName[$i], ",", $DisplayVersion[$i]) | Out-String) ) 
    Add-Content D:\InstalledPrograms.txt $MyOutput
}

当我这样做时,我的输出中包含数组名称,如:

@{Publisher=Adobe Systems Incorporated},@{DisplayName=Adobe AIR},@{DisplayVersion=3.1.0.4880}
(i.e. @{ArrayName ArrayContent}) 

如何摆脱@{ArrayName }并仅保留内容?

1 个答案:

答案 0 :(得分:1)

您得到此信息是因为您将具有属性的对象转换为字符串。使用ex。 $DisplayName[$i].DisplayName方法中的[string]::Concat可以从属性中获取值。

for ($i=0; $i -lt $DisplayName.Count; $i++)
{
    ([string]::Concat($Publisher[$i].Publisher, ",", $DisplayName[$i].DisplayName, ",", $DisplayVersion[$i].DisplayVersion) | Out-String) 
}

输出:

Microsoft Corporation,Microsoft Visual Studio Code,1.10.2

或者您可以在收集值时使用Select-Object -ExpandProperty DisplayName。那将只保留价值。自动取款机。 Select-Object DisplayName等是多余的,因为您仍然必须访问属性才能获得如上所示的值。实施例

$Publisher = Get-ItemProperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Select -ExpandProperty Publisher

但是,我会改写这个。您应该在单个对象中获取安装的所有属性,这样您就可以100%确定这些值属于同一个软件。尝试:

#Get all software in uninstall-key
Get-ItemProperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' |
#Remove empty lines
Where-Object { $_.DisplayName } |
#Arranging the properties in the order you want
Select-Object Publisher, DisplayName, DisplayVersion |
#Export to CSV
Export-Csv -Path "D:\InstalledPrograms.txt" -NoTypeInformation -Append

实施例。 CSV-输出

"Publisher","DisplayName","DisplayVersion"
"Adobe Systems Incorporated","Adobe Flash Player 24 NPAPI","24.0.0.221"
"Tim Kosse","FileZilla Client 3.14.1","3.14.1"
"Microsoft Corporation","Microsoft Help Viewer 2.2","2.2.25123"
"mIRC Co. Ltd.","mIRC","7.43"
"Mozilla","Mozilla Firefox 51.0.1 (x86 en-US)","51.0.1"
"Mozilla","Mozilla Maintenance Service","51.0.1.6234"
"NVIDIA Corporation","NVIDIA Stereoscopic 3D Driver","7.17.13.7500"
"Valve Corporation","Steam","2.10.91.91"
"VideoLAN","VLC media player","2.2.4"

如果输出文件是自定义文件,您可以通过将Export-CSV替换为:

来追加。
#Export to CSV and skip header
ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 |
#Append to file.
Add-Content -Path "D:\InstalledPrograms.txt"