Example Col | Example Col2 |
---|---|
Cell 1 | words : words2 = |
Cell 3 | examplewords:continued |
Hi! I am trying to create a third column where I can get the amount of colons and equal signs in the Example Col2. For example, the first row of the third added column would be 2, and the second row would be 1.
This is what I have tried so far, but I have had no luck. I am really new to PowerShell, so thanks for the help!
CodePudding user response:
If your data comes from a csv file like this:
"Example Col","Example Col2"
"Cell 1","words : words2 ="
"Cell 3","examplewords:continued"
Then you could do
$data = Import-Csv -Path 'X:\Path\example.csv' |
Select-Object *, @{Name = 'Example Col3'; Expression = {
(Select-String -InputObject $_.'Example Col2' -Pattern "[:=]" -AllMatches).Matches.Count}
}
$data
If however you want to use Add-Member
on the objects held in an array in memory, you could loop trhough like
$data | ForEach-Object {
$count = (Select-String -InputObject $_.'Example Col2' -Pattern "[:=]" -AllMatches).Matches.Count
$_ | Add-Member -MemberType NoteProperty -Name 'Example Col3' -Value $count
}
$data
Result:
Example Col Example Col2 Example Col3
----------- ------------ ------------
Cell 1 words : words2 = 2
Cell 3 examplewords:continued 1
CodePudding user response:
Can't say it'd be more efficient than Theo's solution above, but if you wanted an alternative to Select-String matching you could use replace with length property.
$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
}