While answering a question here, I used the following code
$DataFile = Get-Item 'c:\temp\2015-01.csv'
Import-Csv -Path $DataFile -Delimiter ';' |
Measure-Object -Property 'E_TodayKwh' -Sum |
Select-Object @{label="NewName";expression={$DataFile.BaseName '_' $_.Sum $DataFile.Extension}} |
Rename-Item $DataFile
This works, but I was wondering if there was a way to combine the first and second statement, while still being able to reference e.g. $DataFile.BaseName
in the second statement's pipeline. I looked at -PipelineVariable
, but that doesn't seem applicable here (I think?).
CodePudding user response:
I think the best way to approach combining these particular statements is to invert them. That is, instead of Import-Csv
being the "pipeline driver", the operation should be driven by the file input, and Import-Csv
then becomes a contingent operation you can nest in your renaming operation:
Get-Item 'c:\temp\2015-01.csv' |Rename-Item -NewName {'{0}_{1}.{2}' -f $_.BaseName,($_ |Import-Csv -Delimiter ';' |Measure-Object -Sum E_TodayKwh).Sum,$_.Extension}
This way, the operation is also easily adapted to multiple files in the future:
Get-ChildItem -Filter *.csv -Recurse |Rename-Item ...