我有一个从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
2条答案
按热度按时间fquxozlt1#
如果您的CSV看起来像这样:
您可以不循环地更新:
测试结果:
根据not2qubit的注解,对所使用的Select-Object语句进行了一些解释。
因为结果应该反映csv中的所有字段,其中名为
Account
的现有字段值需要替换,所以代码使用Calculated property来设置Account字段值,该值使用查找Hashtable中存储的任何内容。这是使用
@{Name = 'Account'; Expression = {$lookup[$_.Account]}}
完成的接下来,使用星号
*
选择csv中包含的所有其他字段,不做更改。因为我们要覆盖Accound字段,但保留其名称,所以该行以
-ExcludeProperty Account
结尾,以便在输出中删除原始Account字段。如果我们不这样做,PowerShell将显示一个错误:* 选择对象:无法处理该属性,因为属性“帐户”已存在。*wbrvyc0a2#
如果我正确理解了您的要求,您只需要在Import-Csv cmdlet导入的对象中将“001”更改为“Hardware”等。您可以使用switch创建ScriptBlock,switch将根据您搜索的值返回值。我也可以在此处推荐Hashtable,但在本例中,如果未指定默认选项,则可以使用默认选项返回值。例如: