Powershell 循环浏览CSV列

Powershell 循环浏览CSV列,powershell,csv,Powershell,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\D

我有一个简短的脚本,在其中我递归地搜索字符串并写出一些结果。但是,我有数百个字符串要搜索,所以我想从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值?

我想您需要这样的东西

$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行中的第二项)

是否有一个包含多个列的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 | ...
}
对于后者,一个简单的
获取内容
就足够了:

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