2013-08-05 94 views
0

我有一個簡短的腳本中,我遞歸搜索字符串,並寫出了一定的成效。不過我有數百個字符串的搜索,所以我想抓住從一個CSV文件中的值用它作爲我的字符串搜索和移動到下一行。循環通過CSV列

以下是我有:

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 

我如何通過CSV運行指定每行的$ NUM值?

回答

2

您是否有一個包含多個列的CSV文件,其中一個要用作搜索值?或者你有一個「常規」文本文件,每行有一種搜索模式?

在前者的情況下,您可以用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 | ... 
} 

在後面的一個簡單Get-Content的情況下,應該足夠了:

$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 | ... 
} 
0

我認爲你需要像這樣

$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] 
    } 
} 

這將讀取一個CSV文件,並打電話給你的每個線的功能。給出的參數將是csv文件中的值(csv行中的第二項)