简体   繁体   English

Powershell 中带有 export-csv 的 Foreach 循环适用于第一个字段,但不适用于其他字段

[英]Foreach loop with export-csv in Powershell working for first field, but not other fields

I have a PS script that reads a.txt file of pcnames, checks remote registry to report back on the installed programs.我有一个 PS 脚本,它读取 pcnames 的 a.txt 文件,检查远程注册表以报告已安装的程序。 It's partially working when I export it to a.csv file, however only the pcname field changes to the next pcname from my.txt file.当我将它导出到 a.csv 文件时它部分工作,但是只有 pcname 字段更改为 my.txt 文件中的下一个 pcname。 The.csv file is duplicating the same list of installed programs that the first pc in the list has installed. .csv 文件复制了列表中第一台电脑已安装的相同已安装程序列表。 I'm not sure why it is outputting the pcname for each different pc correctly, but the installed program list and version is duplicated for every pc when I view the.csv file.我不确定为什么它正确地为每台不同的 pc 输出 pcname,但是当我查看 .csv 文件时,每台 pc 的安装程序列表和版本都是重复的。 I've tried changing the location of the foreach loops, but haven't had any luck.我试过更改 foreach 循环的位置,但没有成功。 Thanks for any suggestions.感谢您的任何建议。 Here's the code:这是代码:

$pcnames = Get-Content "C:\scripts\pclist.txt"

foreach ($pcname in $pcnames) {


$list=@()
$InstalledSoftwareKey="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
$InstalledSoftware=[microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine',$pcname)
$RegistryKey=$InstalledSoftware.OpenSubKey($InstalledSoftwareKey) 
$SubKeys=$RegistryKey.GetSubKeyNames()

Foreach ($key in $SubKeys){
$thisKey=$InstalledSoftwareKey+"\\"+$key
$thisSubKey=$InstalledSoftware.OpenSubKey($thisKey)
$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name "ComputerName" -Value $pcname
$obj | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $($thisSubKey.GetValue("DisplayName"))
$obj | Add-Member -MemberType NoteProperty -Name "DisplayVersion" -Value $($thisSubKey.GetValue("DisplayVersion"))
$list += $obj 
}
$list | where { $_.DisplayName } | select ComputerName, DisplayName, DisplayVersion | Export-csv 'c:\scripts\allprograms111722.csv' -append
}

I adjusted the closing } for both foreach loops, thinking that would fix the issue, but it did not.我调整了两个 foreach 循环的结束 },以为这样可以解决问题,但事实并非如此。

Your script works for me.你的剧本对我有用。 To be sure that you are not using the content read from the previous computer if a computer in the list is unreachable, you should clear variables between each loop:如果无法访问列表中的计算机,要确保您没有使用从前一台计算机读取的内容,您应该清除每个循环之间的变量:

$list=@()
clear-variable InstalledSoftware
clear-variable SubKeys
clear-variable RegistryKey

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM