更改CSV列中的数据

ki1q1bka  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(226)

我有一个从CSV中提取数据的PowerShell脚本。我尝试执行的操作是根据值“替换”“帐户”列中的数据。例如,帐户001 =硬件,帐户002 =软件等。CSV中的数据是从SQL数据库中提取的,因此,如果在SQL脚本中更改它更容易,我可以很容易地做到这一点。CSV中的帐户列有001,002等。我想改变这些值为硬件,软件等。谢谢帮助。

$Results = import-csv Expenses.csv

$Array = @()       
Foreach($R in $Results)
{
        $Object = [pscustomobject][ordered] @{
 
            Account = $R.Account
            Vendor = $R.Desc1
            Item = $R.Desc2
            Amount = $R.Amount
            
 
        }
        $Array += $Object
}

$Array
fquxozlt

fquxozlt1#

如果您的CSV看起来像这样:

Account,Vendor,Item,Amount
001,Some Vendor,Something expensive, 1
002,Another Vendor,Something cheapish,26

您可以不循环地更新:

# create a lookup hashtable where you combine the account values with the wanted replacement
$lookup = @{
    '001' = 'Hardware'
    '002' = 'Software'
    # etcetera
}
# import the csv and update the `Account` column
$Results = Import-Csv D:\Test\Expenses.csv | Select-Object @{Name = 'Account'; Expression = {$lookup[$_.Account]}}, * -ExcludeProperty Account

# display on screen
$Results
# output to (new) csv file
$Results | Export-Csv -Path D:\Test\Expenses_Updated.csv -NoTypeInformation

测试结果:

Account  Vendor         Item                Amount
-------  ------         ----                ------
Hardware Some Vendor    Something expensive 1     
Software Another Vendor Something cheapish  26

根据not2qubit的注解,对所使用的Select-Object语句进行了一些解释。
因为结果应该反映csv中的所有字段,其中名为Account的现有字段值需要替换,所以代码使用Calculated property来设置Account字段值,该值使用查找Hashtable中存储的任何内容。
这是使用@{Name = 'Account'; Expression = {$lookup[$_.Account]}}完成的
接下来,使用星号*选择csv中包含的所有其他字段,不做更改。
因为我们要覆盖Accound字段,但保留其名称,所以该行以-ExcludeProperty Account结尾,以便在输出中删除原始Account字段。如果我们不这样做,PowerShell将显示一个错误:* 选择对象:无法处理该属性,因为属性“帐户”已存在。*

wbrvyc0a

wbrvyc0a2#

如果我正确理解了您的要求,您只需要在Import-Csv cmdlet导入的对象中将“001”更改为“Hardware”等。您可以使用switch创建ScriptBlockswitch将根据您搜索的值返回值。我也可以在此处推荐Hashtable,但在本例中,如果未指定默认选项,则可以使用默认选项返回值。例如:

$Lookup = {
    Param ([string]$Value)
    
    switch ($Value) {
        "001" { "Hardware" }
        "002" { "Software" }
        default { $Value }
    }
}

$Results = Import-Csv Expenses.csv

foreach($R in $Results)
{
    # Invoke the scriptblock with the named parameter.
    $R.Account = & $Lookup -Value $R.Account
}

# Do stuff with $Results

相关问题