好的,在 Spikeys 最后的评论之后,我开始猜测他可能想要实现的目标。
我创建了一个 CSV 文件:
Product,Template
Microsoft Windows,
RedHat Enterprise,
Apple Safari,
Microsoft Windows,
RedHat Enterprise,
RedHat Enterprise,
然后编写了以下脚本。它被注释并产生以下输出:
Product Template
------- --------
Microsoft Windows Multiple2
RedHat Enterprise Multiple3
Apple Safari Multiple1
Microsoft Windows Multiple2
RedHat Enterprise Multiple3
RedHat Enterprise Multiple3
代码:
$Csv = Import-Csv -Path "C:\Book1.csv"
#Hastables have key - value pairs. Example "Microsoft Windows" = 1. Here 'Microsoft Windows' is the key and '1' is the value
[hashtable]$ProductCount = @{}
#Go through each line in the CSV. This returns the product name e.g. Microsoft Windows
ForEach ($Product in $Csv.Product)
{
#If there us no key for the current product in hashtable $Productcount, then add it with value 1
If ($ProductCount.Keys -notcontains $Product)
{
$ProductCount.Add($Product, 1)
}
#If the above does not apply, then increase the value (effectively the count) by 1
Else
{
$ProductCount[$Product] = $ProductCount[$Product] + 1
}
}
#Go through each row in the CSV file. Each row is returned as it's own object with a 'Product' and 'Template' property
ForEach ($Row in $Csv)
{
#Extract the count for the current product from hastable $ProductCount
$Count = $ProductCount[$Row.Product]
#Set the 'Template' property for the current row object to multipile + the count we got earlier
$Row.Template = "Multiple$Count"
}
#Save the changes to the CSV file as a new CSV. You can also overwrite your old one if you like
$Csv | Export-Csv -Path "C:\Book2.csv"
我不太明白您的问题,但这里有一些我认为在处理 CSV 文件时有用的技巧。
CSV 示例:
Name,City
Bob,BlackPool
Alice,Dover
Carl,Manchester
假设您将 CSV 文件分配给这样的变量
$CSV = Import-CSV -Path "C:\Stuff.csv"
1.您可以通过键入变量点(.)列标题来访问列中的所有行,所以
$CSV.Name
返回:
Bob
Alice
Carl
2.要访问 CSV 文件中的一行,您需要使用索引,所以
$CSV[1]
返回:
Name City
---- ----
Alice Dover
3. 替换特定行的属性的一种简单方法是使用 Where-Object 对其进行过滤。假设我想将卡尔的城市更改为伦敦。
$($CSV | Where-Object {$_.Name -like "Carl"}).City = "London"
会发生什么:
首先处理括号中的内容,因此我们选择 Name 属性类似于“Carl”的行(您可以在此处使用通配符,因此“Ca*”也可以使用)。然后,在括号之外,我们将 city 属性设置为“London”。
注意:$_ 表示当前在管道中的数据,在本例中是包含 Carl 的行。
还有更多需要了解的内容,但这可能对您的帮助最大。
不要忘记使用 Export-CSV cmdlet 保存更改!
$CSV | Export-CSV -Path "C:\new.csv" -NoTypeInformation