如何用PowerShell从CSV首列生成多列并一次性导出完整三列数据
Hey there! Let's break down how to handle these two CSV manipulation tasks with PowerShell—they're actually pretty straightforward once you get the hang of it.
First up, let's assume your input CSV has a header row (required for Import-Csv to work properly) and looks something like this:
Value
5
10
15
The goal is to take that first column (Value here) and generate two new columns, then export everything to a new CSV. Here's how you can do it:
# Read the input CSV file $inputData = Import-Csv -Path "C:\path\to\your\input.csv" # Generate new columns and export the result $inputData | Select-Object *, @{Name = "DoubleValue"; Expression = { [int]$_.Value * 2 } }, @{Name = "SquareValue"; Expression = { [int]$_.Value * [int]$_.Value } } | Export-Csv -Path "C:\path\to\your\output.csv" -NoTypeInformation
Let me break this down for you:
Import-Csvreads your input file and converts each row into a PowerShell object, using the CSV headers as property names.Select-Object *preserves all existing columns (just the first one in this case).- The
@{Name = "..."; Expression = { ... } }blocks are calculated properties—they define the new column names and the logic to generate values using the first column. Export-Csvsaves the final dataset to a new file;-NoTypeInformationremoves the extra type metadata line that PowerShell adds by default.
Just replace Value with your actual first column header, adjust the calculation logic in the expressions, and update the file paths to match your setup.
This task is similar, but since the third column depends on the second, we need to process each row step-by-step to reference the newly generated column. ForEach-Object is perfect for this, as it lets us build each row incrementally.
Using the same input CSV example, let's:
- Take
Value(first column) to generateIncrementedValue(add 10 to the first column) - Use
IncrementedValueto generateTripledValue(multiply the second column by 3)
Here's the code:
Import-Csv -Path "C:\path\to\your\input.csv" | ForEach-Object { # Calculate the second column using the first column's value $secondColumn = [int]$_.Value + 10 # Calculate the third column using the second column's value $thirdColumn = $secondColumn * 3 # Create a new object with all three columns [PSCustomObject]@{ Value = $_.Value IncrementedValue = $secondColumn TripledValue = $thirdColumn } } | Export-Csv -Path "C:\path\to\your\final_output.csv" -NoTypeInformation
What's happening here:
ForEach-Objectprocesses each row individually. We first compute the second column value, then use that result to calculate the third.- We create a
PSCustomObjectthat includes the original first column plus our two new columns. - Finally, we pipe all these objects to
Export-Csvto save the full three-column dataset.
Swap out the column names and calculation logic to match your specific needs—this is just a template to show the core workflow.
内容的提问来源于stack exchange,提问作者Sancha

