2014-12-02 31 views
0

我使用下面的脚本来搜索文件夹内的信用卡号码包含许多子文件夹:PowerShell脚本搜索信用卡号码的文件夹中

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}" 

然而,这将返回找到的所有实例每个文件夹/子文件夹。

我怎样才能修改脚本跳过在一审当前文件夹中发现了什么?这意味着如果它找到一个信用卡号码,它将停止处理当前文件夹并移动到下一个文件夹。

欣赏你的答案和帮助。

由于提前,

+0

@Matt不,这是一个正则表达式。我想他是用它来过滤掉目录或零长度的文件。 – 2014-12-02 15:06:14

+0

@BaconBits我看到了我现在错过的/ r。您需要循环访问每个文件夹,并可能使用布尔值构建退出策略 – Matt 2014-12-02 15:08:40

回答

1

您可以使用此递归函数:

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" 

它会继续通过您指定的顶级目录的子目录中去。每当它到达一个没有子目录的目录,或者它已经通过当前目录的所有子目录时,它将开始查看匹配正则表达式的文件,但是当找到第一个匹配时,将退出该函数。

0

没得充分测试的时间,但我想过这样的事情:

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

所以你真正想要的是每个文件夹中的第一个文件已在信用卡号内容。

打破它分为两个部分。递归获取所有文件夹的列表。然后,对于每个文件夹,以非递归方式获取文件列表。搜索每个文件,直到找到匹配的文件。

我看不出有什么简单的方法单独管道做到这一点。这意味着更传统的编程技术。

这需要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 ($Result -ne $null) { 
      $Found = $true; 
      Write-Output $SearchResult; 
     } 
    } 
} 
0

这是另一个,为什么不,越多越好。

我假设你的正则表达式是正确的。

在第二循环中使用break如果发现将跳过寻找信用卡在剩余的文件,然后继续下一个文件夹。

$path = '<your path here>' 
$folders = Get-ChildItem $path -Directory -rec 

foreach ($folder in $folders) 
{ 
    $items = Get-ChildItem $folder.fullname -File 

    foreach ($i in $items) 
    { 
     if (($found = $i.FullName| select-string "[456][0-9]{15}","[456][0-9]{3}[-| ][0-9]{4} [-| ][0-9]{4}[-| ][0-9]{4}") -ne $null) 
     { 
      break 
     } 
    } 
}