none
Powershell - search cvs for a value and save rows as variables RRS feed

  • Question

  • I am trying to run a powershell script to search a .csv based on input of an office name.  Then save the values in the row for that office to variables to use later.

    $csv = import-csv “C:\TEMP\DHCP.csv”
    ForEach ($Location in $csv){

    $Building = $($Location.Location)
    $Server = $($Location.DHCP_SVR)
    $Scope = $($Location.Scope)


    }
    $Location | where {$_.Building -eq "Office 1"}

    Write-host $Server $scope

    When I run the above it pulls the Office 3 info.

    the .csv is comma delimited, and is simply

    Location      DHCP Server   Scope

    Office 1      Server            10.1.x.x

    Office 2      Server            10.2.x.x

    Office 3      Server            10.3.x.x

    • Moved by Bill_Stewart Friday, July 27, 2018 6:27 PM Abandoned
    Friday, April 27, 2018 8:38 PM

All replies

  • If you don't have a table header "Building" you cannot "search" for it.
    Import-Csv -Delimiter ',' -Path C:\TEMP\DHCP.csv |
        Where-Object -Property Location -EQ -Value 'Office 1'
    If you like to "rename" the properties from your CSV file (for whatever reason) to other "table headers" you could use calclulated properties to do so.

    Best regards,

    (79,108,97,102|%{[char]$_})-join''


    • Edited by BOfH-666 Friday, April 27, 2018 11:22 PM
    Friday, April 27, 2018 11:20 PM
  • There are some basic problems with your logic.  The foreach loop runs through the data from the csv and assigns the values to the variables. Each record wipes out the previous value and you only end up with the last values assigned to the variable.

    The statement

    $Location | where {$_.Building -eq "Office 1"}

    Does nothing since that lable does not exist in the pipeline as BOfH_666 noted.

    The statement

    Write-host $Server $scope

    Displays the last value assigned to $Server and $Scope.  Which is why you get the results you are seeing.

    Try it this way

    $csv = import-csv “C:\TEMP\DHCP.csv”
    ForEach ($Location in $csv){

    $Building = $($Location.Location)
    $Server = $($Location.DHCP_SVR)
    $Scope = $($Location.Scope)
    If ($Building -eq "Office 1") {

        Write-host $Server $scope
    }

    That puts all of the logic inside the loop.

    Monday, April 30, 2018 1:18 PM