在PowerShell中扫描每个文件夹的特定子文件夹

时间:2017-10-17 11:49:11

标签: powershell wildcard

我有这个正常运行的脚本

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\folder_to_scan\"
$watcher.Filter = "*.nrrd"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true  

$action = 
{ 
    $path = $Event.SourceEventArgs.FullPath
    Write-Host "The file '$path' was $changeType at '$(Get-Date)'" -fore green             
}   
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 3600}

但是在我的C:\folder_to_scan\我有很多子目录,例如001230024556002 ......并且在每个子目录中我都有{{1} }}

所以我尝试了这个\THE_DIRECTORY_TO_SCAN$watcher.Path = "C:\folder_to_scan\*\THE_DIRECTORY_TO_SCAN\"

但这不起作用。在这种情况下是否可以使用通配符?

如果没有,如何使用$watcher.Path = "C:\folder_to_scan\[0-9]*\THE_DIRECTORY_TO_SCAN\"的多路径? 因为我发现我们可以使用这个

FileSystemWatcher

3 个答案:

答案 0 :(得分:0)

我不熟悉FileSystemWatcher所以我假设你只需要输入$watcher.Path的文件夹路径

我也假设你的代码已经运行了。

尝试使用Get-ChildItem并使用for循环:

$watcher = New-Object System.IO.FileSystemWatcher
Get-ChildItem "C:\folder_to_scan\" -Recurse | ? { $_.PSIsContainer -and $_.Name.EndsWith("THE_DIRECTORY_TO_SCAN")}| %{ 
    $watcher.Path = $_.FullName #change this
    $watcher.Filter = "*.nrrd"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true  
}
    $action = 
    { 
        $path = $Event.SourceEventArgs.FullPath
        Write-Host "The file '$path' was $changeType at '$(Get-Date)'" -fore green             
    }   
    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 3600} 

答案 1 :(得分:0)

好的,以便澄清我之前谈论的内容。你只是在重复你的等待功能。告诉你我的意思:

    echo "This would be your code running."
    while ($true) {sleep -second 3}

这将打印一次句子,然后每次$ true为真时等待永恒3秒。

您需要做的是:

do{
   echo "This would be your code running."
   sleep -seconds 3
} while($true)

这将每隔3秒打印一次。 或者在你的情况下,每隔3秒运行你的观察者。

答案 2 :(得分:0)

我找不到完美的解决方案所以我这样做了

if ( $path -like '*\THE_DIRECTORY_TO_SCAN\*' ) 
{ Write-Host "File created in \THE_DIRECTORY_TO_SCAN" -fore green }
else
{ Write-Host "File created NOT in \THE_DIRECTORY_TO_SCAN" -fore red }