I created the following command for merge all csv files that matches with a filter inside a folder and outputs it into an outfile.
$mainPath="C:\\users\\myuser\\temp";
$mergeFilter="myfile.csv";
$outFile = "C:\\users\\myuser\temp\test.csv";
Get-ChildItem $mainPath -Recurse -Include $mergeFilter |
Select-Object -ExpandProperty FullName |
Import-Csv -Delimiter ';' |
Select-Object *,@{Name='Date'; Expression={"$dummyvariable"}}; |
Export-Csv $outFile -NoTypeInformation -Delimiter ';'
My issue is that, I want to add an extra column when some CSV's are merged using a variable called $dummyvariable but I dont know where I have to initialize it in order to get the value in the Expression={"..."}. If I declare before in the pipeline it doesn't work (I need to do it higher on the pipe to get a directory name)
Do you know how I can declare this variable and recover on the pipe that starts with "Select-Object"?
Thanks in advance
Best Regards.
Jose
The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
PowerShell Built-in variables $PSItemContains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.
I think you're looking for the -PipelineVariable
(-pv
) common parameter (PSv4+), which stores a given cmdlet's current output object in a variable that can be referenced in script blocks in later pipeline segments.
Here's a simplified example:
# Create sample input file.
@'
foo;bar
1;2
'@ > file.csv
Get-Item file.csv -pv fileObj | Select-Object -ExpandProperty FullName |
Import-Csv -Delimiter ';' | Select-Object *, @{ n='Date'; e={ $fileObj.LastWriteTime } }
The above yields something like:
foo bar Date
--- --- ----
1 2 2/17/18 4:17:25 PM
That is, -pv fileObj
made Get-Item
store its current output object in variable $fileObj
, which the last pipeline segment was able to reference in the property-definition script block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With