• Powershell Search string in csv

    Home » Forums » Developers, developers, developers » DevOps Lounge » Powershell Search string in csv

    Author
    Topic
    #504948

    Hello to all,

    Dear Powershell Experts, i am beginner in powershell scripting, i need your help.

    I want to do a search on csv file containing tow columns, i want to do search on the first column, if name found, perform processing according to the contents of the second column.

    thank you for your kind assidstance.

    Viewing 5 reply threads
    Author
    Replies
    • #1556512

      beginnerScripter,

      Welcome to the Lounge as a new poster! :cheers:

      Here’s some code that demonstrates the handling of CSV files.

      Code:
      #Version: 1.2
      
      $Headers = "A","B","C","D","E"        #One letter for each column!
      $FileLocation = "G:BEKDocsScripts"  #Change to your location!
      $FileFilter = "overall*.csv"          #Change to your filename filter
      
      $FileList = Get-ChildItem $FileLocation -Filter $FileFilter 
      
      ForEach ($FSpec in $FileList) {
        #--- Load File as CSV and add Headers to allow Sorting ---
        (import-csv -Path $FSpec.FullName  -Delimiter '|' -Header $Headers) | `
        Sort-Object C | `
        Export-csv -Path $FSpec.FullName -Delimiter '|' -Force -NoTypeInformation
      
        # Reload File as Text to delete Headers and quotes around values
        # that were added by the CSV processing!
      
        $a = (get-content $FSpec.FullName)
        $a[1..($a.count -1)] -replace '"' | Set-Content $FSpec.FullName
      }
      

      If this isn’t helpful enough post back with a more detailed description of your file (sample data would be useful) and what you want to do the program to do for each instance of the value in column B when column A is matched.

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1556594

      thank you retiredgeek,

      my file is like:
      server,domain
      sever1,domain1
      server2,doamin2
      server3,domain3

      i want to search variable in the column server if match i want to display the column domaine in the same line

      I wrote this code but it does not give me the desired result

      $records = Import-Csv C:antemetaSrv2Backup.csv -Delimiter “;”
      $Srv=Read-Host “give the name of the server”
      ForEach ($record in $records)
      {
      $name=$record.name

      if ( $srv = $name ) {write-host $record.domain}

      }

      can you help me please

    • #1556654

      Ok, let’s look at this and see what is going wrong.

      First thing you what to get in the habit of doing is to use the Get-Member cmdlet to see what your Object looks like. So once you have load the file into the object $Records you test it to see what it looks like:

      Code:
      PS> $records | Get-Member
      
      
         TypeName: System.Management.Automation.PSCustomObject
      
      Name        MemberType   Definition                    
      ----        ----------   ----------                    
      Equals      Method       bool Equals(System.Object obj)
      GetHashCode Method       int GetHashCode()             
      GetType     Method       type GetType()                
      ToString    Method       string ToString()             
      domain      NoteProperty string domain=domain1         
      server      NoteProperty string server=sever1  
      

      From the above you can see that it has taken the first line of your file (imported as a csv) and used it as the column titles.

      This means that to reference those items you need to use $Records.Server & $Records.Domain.

      Next you need to remember that in PowerShell the = sign is used for assignment NOT testing! For testing you use the operators -eq, -ne, -gt, etc.

      Lastly, if you look at your file you use a comma as the delimiter but in your code you told it to look for a semi-colon.

      So incorporating all those factors the code looks like this:

      Code:
      $records = Import-Csv G:Testdomains.csv -Delimiter ","
      $Srv=Read-Host "give the name of the server"
      ForEach ($record in $records)
      {
      
      if ( $Record.Server -eq $Srv ) {write-host $record.domain}
      
      }
      

      A test run looks like this:

      Code:
      give the name of the server: Server2
      doamin2
      

      Another way to code the same thing, although not as efficient would be:

      Code:
      $records = Import-Csv G:Testdomains.csv -Delimiter ","
      $Srv=Read-Host "give the name of the server"
      
      
      For ($Cnt = 1 ; $cnt -lt $Records.Count; $Cnt++)
      {
        
      if ( $records[$Cnt].server -eq $Srv ) {write-host $records[$Cnt].domain}
      
      } #End For ($Cnt...
      

      I hope this helps you in your quest to learn PS. Please post back if you have more question.

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1556659

      thank thank you retiredgeek,

      Your explanation helped me understand the functioning of powershell, I could get the result through this code:

      $records = Import-Csv C:Srv2Backup.csv -Delimiter “;”
      $Srv=Read-Host “give the name of the server”
      $aa=forEach-Object {$records | Select serveur, domaine | where serveur -eq $Srv }
      $bb=forEach-Object {$aa | Select domaine }

      if ($bb.Domaine -eq “domain1”) {Write-Host “c’est un domaine domain1”}
      elseif ($bb.Domaine -eq “domain2”) {Write-Host “c’est un domaine domain2”}
      else {Write-Host “c’est un Workgroupe”}

      thank you retiredgeek 🙂

    • #1556660

      beginnerScripter,

      Not a good Idea to switch languages in the middle of a thread…a bit confusing for us single (spoken) language folks. 😆

      That code does work but is a bit inefficient.

      How about this code:

      Code:
      $records = Import-Csv G:Testdomains.csv -Delimiter ","
      $Srv=Read-Host "give the name of the server"
      
      ForEach ($record in $records)
      {
        if ( $Record.Server -eq $Srv ) {$MatchedDomain = $record.domain}
      }
      
      If (Test-Path Variable:MatchedDomain) {
        Write-Host "The domain for server $Srv is $MatchedDomain"
        Remove-Variable MatchedDomain
      }
      Else {
        Write-Host "The server $Srv does not exist in the file."
      }
      

      Note: the Remove-Variable statement. This makes sure the $MatchedDomain doesn’t hang around if you rerun the code in the same PS session. With out this if you rerun the code in the same session after a matched server and then enter a server which is not in the list it would return the last matched value as the check for the existence of $MatchedDomain (Test-Path Variable:MatchedDomain) would find the variable still in existence.

      Example runs:

      Code:
      give the name of the server: Server3
      The domain for server Server3 is domain3
      
      give the name of the server: Server4
      The server Server4 does not exist in the file.
      

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1556729

      thank you retiredgeek

    Viewing 5 reply threads
    Reply To: Powershell Search string in csv

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: