Reputation: 1458
I have to create a report which reads two different files, they are .properties
files, one is custom version of the original. I am currently reading both files using Get-Content
and pass it to pileline and foreach-object
ing and here I am creating a new [pscustomobject]
. It is working fine for original file, but I am not able to add the custom version of the file:
$config = Get-Content -Path 'D:\Config.properties'
$custom = Get-Content -Path 'D:\Custom\Config.properties'
$orig_obj = $config | % {
$item = $_ -split '=';
$features = [PSCustomObject]@{
'Server' = "$(hostname.exe)"
'Feature' = $item[0]
'Value' = $item[1]
}
$feature
}
Above returns this:
Server ConfFeature ConfValue
------ ----------- ---------
srv1 client.number 111
srv1 FEAT1 101
Now I want to do the custom
file , but I want to add the features
and values
as a new columns to the above output:
Server ConfFeature ConfValue CustomFeature CustomValue
------ ----------- --------- ------------- -----------
srv1 FEAT2 111 FEAT2 222
srv1 FEAT1 101 FEAT1 201
how do I add the new columns?
Upvotes: 0
Views: 325
Reputation: 17462
I suppose you want cross by feature...
#import and split by '=' and add header Fetaure and value
$custom = import-csv 'D:\Config.properties' -Delimiter '=' -Header Feature, Value
#import and split by '=' and add header Fetaure and value and add property Server, CustomFeature CustomValue
$config = import-csv -Path 'D:\Custom\Config.properties' -Delimiter '=' -Header Feature, Value, Server, CustomFeature CustomValue
$Result_obj = $config | %{
#set hostname
$_.Server=$env:COMPUTERNAME
$CurrentFeature = $_.Feature
#take first row with the same feature into custom file
$CustomItem=$custom | where Feature -eq $CurrentFeature | select -First 1
if ($CustomItem -eq $null)
{
$_.CustomFeature=$null
$_.CustomValue=$null
}
else
{
$_.CustomFeature=$CustomItem.Feature
$_.CustomValue=$CustomItem.Value
}
$_
}
#show result
$Result_obj
Upvotes: 1
Reputation: 366
To create new "columns" you'll want to use the Add-Member command. What you will actually be doing is adding new properties to the existing object. Here's an example:
$feature | Add-Member -NotePropertyName "ColumnName" -NotePropertyValue "Value"
Here's a link to the Add-Member documentation: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/add-member?view=powershell-7.1
Upvotes: 0