简体   繁体   中英

PowerShell, How to combine two sets of unrelated data into one array or csv

I'm trying to write a simple powershell script to pull software and service data off a machine. So I'm trying to figure out the best way to consolidate the data onto one cvs file instead of two separate csv files. I wanted to use the below, but it would save time in the end for both sets of data to be combined.

Get-Services | Select StartType, Status, Name, DisplayName |
Export-CSV -path $servicescsv

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | 
Export-CSV -path $softwarecsv

So the above is probably quite simple, but I could just create two arrays for software and services. But then what is the best method to combine the two arrays without writing over each other? I know one of the issues is that DisplayName for software conflicts with DisplayName for services. So right now $array3 = $services + $software only adds the software display name to the array, but the other columns are lost.

What is the best approach to this problem?

Without an example, of the current CSV files and your desired output, it's not clear what your intended goal is.

I think you could accomplish what you're trying to do like this:

Get-Service |
    Select-Object StartType, Status, Name, DisplayName, DisplayVersion, Publisher, InstallDate |
    Export-CSV -Path $CombinedCsv

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
    Select-Object StartType, Status, Name, DisplayName, DisplayVersion, Publisher, InstallDate |
    Export-CSV -Path $CombinedCSV -Append

The issue is that Export-Csv uses the first objects in the pipeline to identify the available properties. If you need to include properties that don't exist at the start, you should specify all of them. That will cause Select-Object to create new properties that are blank, which will then export appropriately to CSV.

If, on the other hand, your goal is to try to join $servicescsv and $softwarecsv like two SQL tables with a common field... well, you can do that but it's significantly more complicated and requires key fields to join on. I don't think the DisplayName property of the registry key you list and the services module are very likely to agree on a name. Especially because lots of entries in the registry don't have a DisplayName.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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