示例列 | 示例列2 |
---|---|
单元格1 | words:words2= |
单元格3 | 示例单词:continued |
不能说它会比Theo上面的解决方案更有效,但如果你想要一个替代SelectString匹配的方法,你可以使用replacewithlength属性。
$data = $(
[PSCustomObject]@{ 'Example Col' = 'Cell 1'; 'Example Col2' = 'words : words2 =' }
[PSCustomObject]@{ 'Example Col' = 'Cell 3'; 'Example Col2' = 'examplewords:continued' }
)
$data | ForEach-Object {
$_ | Add-Member -MemberType NoteProperty -Name 'Example Col3' -Value ($_.'Example Col2' -replace '[^:=]').Length
}
如果您的数据来自这样的csv文件:
"Example Col","Example Col2"
"Cell 1","words : words2 ="
"Cell 3","examplewords:continued"
然后你可以做
$data = Import-Csv -Path 'X:Pathexample.csv' |
Select-Object *, @{Name = 'Example Col3'; Expression = {
# (Select-String -InputObject $_.'Example Col2' -Pattern "[:=]" -AllMatches).Matches.Count}
# a faster option:
[regex]::Matches($_.'Example Col2', '[:=]').Groups.Count }
}
$data
然而,如果你想在内存中数组中的对象上使用Add-Member
,你可以像一样循环trhough
$data | ForEach-Object {
# $count = (Select-String -InputObject $_.'Example Col2' -Pattern "[:=]" -AllMatches).Matches.Count
# a faster option:
$count = [regex]::Matches($_.'Example Col2', '[:=]').Groups.Count
$_ | Add-Member -MemberType NoteProperty -Name 'Example Col3' -Value $count
}
$data
结果:
Example Col Example Col2 Example Col3
----------- ------------ ------------
Cell 1 words : words2 = 2
Cell 3 examplewords:continued 1