Home > Blockchain >  Get specific item from a match of select-string
Get specific item from a match of select-string

Time:10-13

I have a csv file. I am searching for a value using select-string. I need to identify the returned value on a specific column the $Line[Cui]

$sLine= New-Object System.Collections.Hashtable
$sText = @"
Vendorid,Cui,Data,iStaus,CashVat
404,20955366,2022-08-11,1,True
1025,15293910,2022-08-11,-1,False
2022,27684873,2022-08-11,2,True
3055,29195059,2022-08-11,3,False
"@;
$csvText= $sText | ConvertFrom-csv -Delimiter ','
$sLine = $csvText |Select-string -Pattern '15293910' -SimpleMatch -Encoding utf8 

The found object looks like a hashtable

'=====Match is is======='
 $sLine
'=====Match was======='

The returned value is
=====Match is is=======
@{Vendorid=1025; Cui=15293910; Data=2022-08-11; iStaus=-1; CashVat=False}
=====Match was=======

But there following code line does not return a value

'=====Get the desired value for the key======='
 $sLine['CashVat'].value
'================================='

Returns nothing in debug window

Also the the GetEnumerator does not return a key value pair

 $sLine.GetEnumerator() | ForEach-Object {
                          $message = '{0} is key {1} value' -f $_.key, $_.value
                          write-output $message
                         }  

Just lists the <> 73 times which is equivalent to the lengths of $sLine variable Looks like the $sLine is just a line of text and not in hashtable format

CodePudding user response:

$sLine is not a hashtable but MatchInfo object reurned by Select-String.

Ther other thing sls does here, is converting every object in array to string representation, and then matching the value. So it'll also match curly braces, semicolons and property names in that string.

But if you already converted csv text to array of objects, you could search it directly, no need to use select-string: $csvText | Where-Object Cui -EQ '15293910'

Or use select-string on raw csv: $sls = $sText | Select-String '15293910' If you skip -SimpleMatch, you'll have captured text in MatchInfo: $sls.Matches (this applies to your original example, too).

CodePudding user response:

You can use the Where selector.

$sLine = $csvText | where {$_.Cui -eq 15293910}
$sLine.CashVat 

That will return False

  • Related