在现有列 powershell 中添加新行

问题描述 投票:0回答:1

我有一个包含三列的 csv 文件,如下所示:

日期 活跃 不活跃
1/14/24 200 300
1/15/24 250 350

我试图为三列中的每一列添加一个新行,同时保留所有以前的值。新行必须使用 get-date 作为当前日期,并且“活动”值为 400,“非活动”值为 500。

下面我有一个类似的脚本,但仅添加一个新列(而不是现有列的行)。非常感谢有关修改此脚本以仅在现有列中添加包含请求值的新行的任何帮助!

# Get today's date in the desired format for the new column name
$NewColumnName = Get-Date -Format 'yyyy-MM-dd'

# Import the CSV file AND add an empty "date" column
$Data = Import-Csv -Path $CsvPath | Select-Object -Property Date, @{n = "$newColumnName"; e = { $null } }

# array of the values you want to add.
# you could add each by themselves but this scales better if you go beyond a few rows
$NewValues = @(
    '400'
    '500'
)

# setting up the index variable
$LoopIndex = 0

# cycle through the elements in `$data`
$Data | ForEach-Object {
    # `$_` is the name for the object of the current iteration of the loop
    $_.$NewColumnName = $NewValues[$LoopIndex++]
}

##EXPORT # Get today's date in the desired format for the new column name
$NewColumnName = Get-Date -Format 'yyyy-MM-dd'

# Import the CSV file AND add an empty "today" column
$Data = Import-Csv -Path $CsvPath | Select-Object -Property Date, @{n = "$newColumnName"; e = { $null } }

# array of the values you want to add.
# you could add each by themselves but this scales better if you go beyond a few rows
$NewValues = @(
    '400'
    '500'
)

# setting up the index variable
$LoopIndex = 0

# cycle through the elements in `$data`
$Data | ForEach-Object {
    # `$_` is the name for the object of the current iteration of the loop
    $_.$NewColumnName = $NewValues[$LoopIndex++]
}

##EXPORT 
powershell csv foreach
1个回答
0
投票

您所需要的只是带有

Export-Csv
:
-Append

cmdlet
$value = [PSCustomObject]@{
    Date = Get-Date -Format 'M/d/yy'
    Active = 400
    Inactive = 500
}
$value | Export-Csv -Path $CsvPath -Append -NoTypeInformation
© www.soinside.com 2019 - 2024. All rights reserved.