SimonS
SimonS

Reputation: 1973

Computernames in Export-CSV in ForEach-Object

I'm trying to get the installed .NET Framework version of each of the Computers in my ComputerNames.csv File. That's my Code so far:

$ComputerNames = Import-csv $ListPath\ComputerNames.csv
$ComputerNames | ForEach-Object {
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version -EA 0 |
# Where { $_.PSChildName -match '^(?!S)\p{L}'} |
Select Version
} | Export-Csv "$ExportPath\FrameWorkVersion-$DateTime.csv"

When I run this code, it creates a CSV Output of all the installed .NET Framework Versions, which is nice. But i'd like to have it sortet to the computername.

It's difficult for me to explain this in english so here's an example:

Output so far:

TYPE Selected.System.Management.Automation.PSCustomObject
Version
2.0.50727.4927
2.0.50727.4927
3.0.30729.4926
3.0.30729.4926
3.0.30729.7903
3.0.4506.4926
3.0.6920.4902
3.5.30729.4926
3.5.30729.5003
4.5.51641
4.5.51641
4.5.51641

I'd like to have it like this:

TYPE Selected.System.Management.Automation.PSCustomObject
Version
Computer 1
2.0.50727.4927
2.0.50727.4927
3.0.30729.4926
3.0.30729.4926
3.0.30729.7903
Computer 2
3.0.4506.4926
3.0.6920.4902
3.5.30729.4926
3.5.30729.5003
4.5.51641
Computer 3
4.5.51641
4.5.51641

Is that possible?

Upvotes: 0

Views: 535

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

As pointed out in the comments, you might be piping your computer names to ForEach-Object but you're not using them for anything, so effectively, you're re-running the same query on your own machine a number of times.

You can use Invoke-Command to run the script on remote machines, like this:

$ComputerNames = Import-csv $ListPath\ComputerNames.csv
$ComputerNames | ForEach-Object {
    # $_ refers to the current item in the pipeline, in this case, an object with a computer name in the "name" property
    $ComputerName = $_.Name
    $ScriptBlock = {
        Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version -EA 0 | Select-Object Version
    }
    # This is where the magic happens
    Invoke-Command -ComputerName $ComputerName -ScriptBlock $ScriptBlock | Select @{Name="Computer";Expression = { $ComputerName } },Version
} | Export-Csv "$ExportPath\FrameWorkVersion-$DateTime.csv" -NoTypeInformation

Now, thanks to the calculated property @{Name="Computer";Expression={$ComputerName}} in the select statement after Invoke-Command, you csv will have a "Computer" column and a "Version" column

Upvotes: 1

Related Questions