Powershell 将字符串搜索结果附加到现有csv文件
我想在多个文件夹中搜索包含特定字符串的文件。每个文件夹的名称都列在一个csv文件thelist.csv中,该文件有一个标题列表1。我想将搜索结果附加到list.csv,为FileName Result1和Directory Result2添加一列。我试图进入csv文件或excel工作表,以便最终确定哪些文件夹包含/不包含“TestString.txt”文件 示例代码:Powershell 将字符串搜索结果附加到现有csv文件,powershell,csv,powershell-2.0,Powershell,Csv,Powershell 2.0,我想在多个文件夹中搜索包含特定字符串的文件。每个文件夹的名称都列在一个csv文件thelist.csv中,该文件有一个标题列表1。我想将搜索结果附加到list.csv,为FileName Result1和Directory Result2添加一列。我试图进入csv文件或excel工作表,以便最终确定哪些文件夹包含/不包含“TestString.txt”文件 示例代码: 搜索缺少的字符串成功返回结果,包括文件名result1和目录result2。但是,我在将结果附加到csv文件时遇到问题。现在,我
搜索缺少的字符串成功返回结果,包括文件名result1和目录result2。但是,我在将结果附加到csv文件时遇到问题。现在,我的代码从原始列表返回List1的空值。原始csv文件中唯一存在的数据是标题 您的代码试图从文件名中提取属性List1、Results1、Results2,但没有任何代码告诉它如何这样做,因此它们是空的 您正在尝试在循环内进行导出,删除文件并在每次搜索时覆盖它,这样它只会有一个结果 您可能需要处理一个搜索返回多个匹配文件的情况,这需要向CSV添加新行 我没有尝试过这段代码,但这种方法应该更接近您想要的:
# Import from single column file, calling the column 'List1', and process each line:
Import-Csv -LiteralPath C:\The\Path\thelist.csv -Header List1 | ForEach-Object {
# store line with a name, for use later on
$Line = $_
# the folders coming in from the CSV are in the column 'List1', search them
Get-ChildItem -LiteralPath $Line.List1 -Filter *TestString* -Recurse | ForEach-Object {
# for each search result TestString.txt, make a hashtable
# representing a new line in the output CSV, with the new data,
# and convert to PS Custom Object so it will work with Export-CSV later on.
[PSCustomObject]@{
'List1' = $Line.List1
'Result1' = $_.Name
'Result2' = $_.DirectoryName
}
}
# at the end of both loops, export all the results in one go
} | Export-csv C:\The\Path\thelist2.csv -NoTypeInformation
# Import from single column file, calling the column 'List1', and process each line:
Import-Csv -LiteralPath C:\The\Path\thelist.csv -Header List1 | ForEach-Object {
# store line with a name, for use later on
$Line = $_
# the folders coming in from the CSV are in the column 'List1', search them
Get-ChildItem -LiteralPath $Line.List1 -Filter *TestString* -Recurse | ForEach-Object {
# for each search result TestString.txt, make a hashtable
# representing a new line in the output CSV, with the new data,
# and convert to PS Custom Object so it will work with Export-CSV later on.
[PSCustomObject]@{
'List1' = $Line.List1
'Result1' = $_.Name
'Result2' = $_.DirectoryName
}
}
# at the end of both loops, export all the results in one go
} | Export-csv C:\The\Path\thelist2.csv -NoTypeInformation