简体   繁体   中英

Loop through a CSV Column

I have a short script in which I am recursively searching for a string and writing out some results. However I have hundreds of strings to search for, so I would like to grab the value from a CSV file use it as my string search and move to the next row.

Here is what I have:

function searchNum {
#I would like to go from manual number input to auto assign from CSV
$num = Read-Host 'Please input the number'
get-childitem "C:\Users\user\Desktop\SearchFolder\input" -recurse | Select String -pattern "$num" -context 2 | Out-File "C:\Users\user\Desktop\SearchFolder\output\output.txt" -width 300 -Append -NoClobber
}

searchNum

How can I run through a CSV to assign the $num value for each line?

Do you have a CSV with several columns, one of which you want to use as search values? Or do you have a "regular" text file with one search pattern per line?

In case of the former, you could read the file with Import-Csv :

$filename   = 'C:\path\to\your.csv'
$searchRoot = 'C:\Users\user\Desktop\SearchFolder\input'

foreach ($pattern in (Import-Csv $filename | % {$_.colname})) {
  Get-ChildItem $searchRoot -Recurse | Select-String $pattern -Context 2 | ...
}

In case of the latter a simple Get-Content should suffice:

$filename   = 'C:\path\to\your.txt'
$searchRoot = 'C:\Users\user\Desktop\SearchFolder\input'

foreach ($pattern in (Get-Content $filename})) {
  Get-ChildItem $searchRoot -Recurse | Select-String $pattern -Context 2 | ...
}

I assume you need something like this

$csvFile = Get-Content -Path "myCSVfile.csv"
foreach($line in $csvFile)
{
    $lineArray = $line.Split(",")
    if ($lineArray -and $lineArray.Count -gt 1)
    {
        #Do a search num with the value from the csv file
        searchNum -num $lineArray[1]
    }
}

This will read a csv file and call you function for each line. The parameter given will be the value in the csv file (the second item on the csv line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM