我有一个 PowerShell 脚本从 CSV 中提取数据。我想做的是根据值“替换”帐户列中的数据。例如,帐户 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
Run Code Online (Sandbox Code Playgroud)
如果您的 CSV 看起来像这样:
Account,Vendor,Item,Amount
001,Some Vendor,Something expensive, 1
002,Another Vendor,Something cheapish,26
Run Code Online (Sandbox Code Playgroud)
您可以不循环更新:
# 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
Run Code Online (Sandbox Code Playgroud)
结果:
Account Vendor Item Amount
------- ------ ---- ------
Hardware Some Vendor Something expensive 1
Software Another Vendor Something cheapish 26
Run Code Online (Sandbox Code Playgroud)
根据not2qubit的评论,对所使用的 Select-Object 语句进行了一些解释。
由于结果应反映 csv 中的所有字段,其中Account需要替换指定的现有字段值,因此代码使用计算属性来使用查找哈希表中存储的任何内容来设置帐户字段值。
这是用完成的@{Name = 'Account'; Expression = {$lookup[$_.Account]}}
接下来,使用星号原封不动地选择 csv 中包含的所有其他字段*。
因为我们要覆盖 Accound 字段,但保留其名称,所以该行以 结尾,-ExcludeProperty Account以便删除输出中的原始Account 字段。如果我们不这样做,PowerShell 将显示错误:Select-Object :无法处理该属性,因为属性“Account”已存在。