Powershell extends an object

How to add a column to an object in PowerShell?

For example, Get-Childitem returns an object with a mode, LastWriteTime, Length Name, etc. .... And I want to expand this object with an additional column, which is calculated from LastWriteTime.

This is the original output of Get-Childitem:

Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 2012.12.15. 17:02 5390 Log_20121215.txt -a--- 2013.01.02. 17:10 14014 Log_20130102.txt -a--- 2013.01.07. 17:08 2200 Log_20130107.txt 

And I want this conclusion:

 Mode LastWriteTime Length Name ComputedColumn ---- ------------- ------ ---- -------------- -a--- 2012.12.15. 17:02 5390 Telenor_Log_20121215.txt 20131215 -a--- 2013.01.02. 17:10 14014 Telenor_Log_20130102.txt 20140102 -a--- 2013.01.07. 17:08 2200 Telenor_Log_20130107.txt 20140207 

Thanks for any help.

+4
source share
2 answers

Use an Add-Member or custom expression in select , depending on how you need it.

Calculate and save. Saves the original object, but adds one custom column

 $data = dir | % { Add-Member -InputObject $_ -MemberType NoteProperty -Name "ComputedColumn" -Value $_.LastWriteTime.AddYears(1).ToString("yyyyMMdd") -PassThru } 

Compute it before displaying (or export to csv, etc.)

 dir | select Mode, LastWriteTime, Length, Name, @{name="ComputedColumn";expression={ $_.LastWriteTime.AddYears(1).ToString("yyyyMMdd") }} 

Ex. with format table for proper display

 dir | select Mode, LastWriteTime, Length, Name, @{name="ComputedColumn";expression={ $_.LastWriteTime.AddYears(1).ToString("yyyyMMdd") }} | ft -AutoSize Mode LastWriteTime Length Name ComputedColumn ---- ------------- ------ ---- -------------- dr-- 14.04.2013 17:47:18 Contacts 20140414 dr-- 15.05.2013 14:19:45 Desktop 20140515 dr-- 14.04.2013 18:03:33 Documents 20140414 dr-- 11.05.2013 18:22:57 Downloads 20140511 
+10
source

The easiest way to extend an object is to pass it to the Select-Object cmdlet. See the example below.

 # Add the extended property IsVeryBig Get-ChildItem c:\temp | Select-Object *, IsVeryBig | For-EachObject { $_.IsVeryBig = $True } 
0
source

Source: https://habr.com/ru/post/1480947/


All Articles