Home > Blockchain >  Powershell - Check if Value in CSV exists
Powershell - Check if Value in CSV exists

Time:11-01

I want to check if a string exists in a csv file.

I'm trying to use if ($PCname -in $logFileLocation) { write-output "true" } else { write-output "false" }

However this always returns false.

How can I check for a value within a csv file?

CodePudding user response:

You can integrate a query within the result of dir ( Get-Childitem )

$Query = "yourString"
$List = Get-Childitem *.CSV |
Select-Object Name,@{Name="MatchesQuery"; Expression={($_ | Get-Content -raw) -match $Query}}
$List

Attention: $Query will be interpreted as regular expression

That way you get a list of all files with the information that it is matching your cirteria or not. That way you can filter afterwards like that:

$List | where {$_.MatchesQuery -eq $true}

Depending in your CSV it might be better and more relyable if you do not only Get-Content but use ConvertFrom-CSV and select the column you want to search in.

This version reads CSV and searches the column "ComputerName" for your $Query

$Query = "yourString"
$List = Get-Childitem *.CSV | Select-Object Name,@{Name="MatchesQuery"; Expression={($_ | Get-Content -raw | ConvertFrom-CSV -Delimiter ";" | where {$_.ComputerName -eq "$Query").Count -gt 0}}}
$List

CodePudding user response:

this could be helpful:

$find = "some_string"
Get-Content C:\temp\demo.csv | Select-String $find
  • Related