[英]How do I add new properties to an existing custom object and add values to the newly added properties in Powershell?
I have to create a report which reads two different files, they are .properties
files, one is custom version of the original.我必须创建一个读取两个不同文件的报告,它们是
.properties
文件,一个是原始文件的自定义版本。 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]
.我目前正在使用
Get-Content
读取这两个文件并将其传递给 pileline 和foreach-object
,在这里我正在创建一个新的[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:现在我想做
custom
文件,但我想将features
和values
作为新列添加到上面的 output 中:
Server ConfFeature ConfValue CustomFeature CustomValue
------ ----------- --------- ------------- -----------
srv1 FEAT2 111 FEAT2 222
srv1 FEAT1 101 FEAT1 201
how do I add the new columns?如何添加新列?
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
To create new "columns" you'll want to use the Add-Member command.要创建新的“列”,您需要使用 Add-Member 命令。 What you will actually be doing is adding new properties to the existing object.
您实际上要做的是向现有的 object 添加新属性。 Here's an example:
这是一个例子:
$feature | Add-Member -NotePropertyName "ColumnName" -NotePropertyValue "Value"
Here's a link to the Add-Member documentation: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/add-member?view=powershell-7.1这是添加成员文档的链接: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/add-member?view=powershell-7.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.