我正在使用以下脚本在包含许多子文件夹的文件夹中搜索信用卡号码:
Get-ChildItem -rec | ?{ findstr.exe /mprc:. $_.FullName }
| select-string "[456][0-9]{15}","[456][0-9]{3}[-| ][0-9]{4} [-| ][0-9]{4}[-| ][0-9]{4}"但是,这将返回在每个文件夹/子文件夹中找到的所有实例。
如何修改脚本以跳过第一次找到的当前文件夹?这意味着,如果它找到一个信用卡号,它将停止处理当前文件夹,并移动到下一个文件夹。
感谢您的回答和帮助。
提前谢谢你,
发布于 2014-12-02 23:15:45
你可以使用这个递归函数:
function cards ($dir)
Get-ChildItem -Directory $dir | % { cards($_.FullName) }
Get-ChildItem -File $dir\* | % {
if ( Select-String $_.FullName "[456][0-9]{15}","[456][0-9]{3}[-| ][0-9]{4} [-| ][0-9]{4}[-| ][0-9]{4}" ) {
write-host "card found in $dir"
return
}
}
}
cards "C:\path\to\base\dir"它将继续遍历您指定的顶级目录的子目录。每当它到达一个没有子目录的目录,或者它遍历了当前目录的所有子目录时,它将开始在文件中查找匹配的regex,但当找到第一个匹配时,它将退出函数。
发布于 2014-12-02 23:27:10
因此,您真正想要的是每个文件夹中的第一个文件,该文件的内容中包含信用卡号。
把它分成两部分。以递归方式获取所有文件夹的列表。然后,对于每个文件夹,以非递归方式获取文件列表。搜索每个文件,直到找到匹配的文件。
我没有看到任何简单的方法来做到这一点与管道单独。这意味着更传统的编程技术。
这需要PowerShell 3.0。我去掉了?{ findstr.exe /mprc:. $_.FullName },因为我能看到它所做的就是去掉文件夹(和零长度文件),而它已经处理了这个问题。
Get-ChildItem -Directory -Recurse | ForEach-Object {
$Found = $false;
$i = 0;
$Files = $_ | Get-ChildItem -File | Sort-Object -Property Name;
for ($i = 0; ($Files[$i] -ne $null) -and ($Found -eq $false); $i++) {
$SearchResult = $Files[$i] | Select-String "[456][0-9]{15}","[456][0-9]{3}[-| ][0-9]{4} [-| ][0-9]{4}[-| ][0-9]{4}";
if ($SearchResult) {
$Found = $true;
Write-Output $SearchResult;
}
}
}发布于 2014-12-02 23:26:49
我没有时间对其进行全面测试,但我想了想:
$Location = 'H:\'
$Dirs = Get-ChildItem $Location -Directory -Recurse
$Regex1 = "[456][0-9]{3}[-| ][0-9]{4} [-| ][0-9]{4}[-| ][0-9]{4}"
$Regex2 = "[456][0-9]{15}"
Foreach ($d in $Dirs) {
$Files = Get-ChildItem $d.FullName -File
foreach ($f in $Files) {
if (($f.Name -match $Regex1) -or ($f.Name -match $Regex2)) {
Write-Host 'Match found'
Return
}
}
}https://stackoverflow.com/questions/27251961
复制相似问题