Automation

 View Only
  • 1.  Using CSV files

    Posted Apr 28, 2020 11:08 AM

    Little help please,

    I am writing a script to look at a csv file and if a certain value exists then do something, but in doing something the script would need to pull the information from that same column. Below is an example bit of code, from this i want the script to look at that csv file and if it finds a value of test3 to return the value in the IPAddr column of the same row...

    "Name","Hostname","IPAddr"

    "test1","testing1","1.1.1.1"

    "test2","testing2","2.2.2.2"

    "test3","testing3","3.3.3.3"

    $testcsv = import-csv "C:\Rich\Test.csv"

    $hostname = "test3"

    $Output = @()

    where-object ($hostname -eq $testcsv.Name) {

    $output += $testcsv.name

    $output += $testcsv.IPAddr

    }

    $Output | out-file "C:\Rich\testoutput.txt"



  • 2.  RE: Using CSV files
    Best Answer

    Posted Apr 28, 2020 11:17 AM

    You mean something like this?
    It uses a Where-clause to only handle the lines that fit the test.

    $hostname = "test3"

    $output = @()


    Import-Csv "C:\Rich\Test.csv" -UseCulture |

    where{$_.Name -eq $hostname} |

    ForEach-Object -Process {

        $output += $_.name

        $output += $_.IPAddr

    }


    $Output | Out-File "C:\Rich\testoutput.txt"



  • 3.  RE: Using CSV files

    Posted Apr 28, 2020 11:29 AM

    that was incredibly useful and thank you for the quick reply



  • 4.  RE: Using CSV files

    Posted Apr 28, 2020 03:22 PM

    One more thing sorry,

    How could i move the actual method to a function or can you not do that because of the way its referencing the csv

    $hostname = "test3"

    $Output = @()

    function outputfn {

    $output += $_.Name

    $output += $_.IPAddr

    }

    import-csv "C:\Rich\Test.csv" -UseCulture | where{$_.Name -eq $hostname} | foreach-object -process {

    #$output += $_.Name

    #$output += $_.IPAddr

    outputfn

    }

    $Output | out-file "C:\Rich\testoutput.txt"



  • 5.  RE: Using CSV files

    Posted Apr 28, 2020 04:32 PM

    No problem.

    You could use a function like this for example

    function Get-Output {

        param(

            [string]$Path,

            [string]$HostName

        )


        Import-Csv $Path -UseCulture |

        where{$_.Name -eq $HostName} |

        ForEach-Object -Process {

            $_.name

            $_.IPAddr

        }

    }


    Get-Output -Path "C:\Rich\Test.csv" -HostName "test3" |

    Out-File "C:\Rich\testoutput.txt"