1

我正在编写一个脚本来删除文件夹中带有“电子邮件”前缀的 6 个月以上的 pdf 文件。

但是,我的 foreach 中的第二个 dir 命令从未运行,它的代码被阻止。

$Now = Get-Date;
$DaysTillDelete = "180";
$LastWrite = $Now.AddDays(-$DaysTillDelete);
$TargetFolder = "C:\Test EMDATA\EMDATA\";
$BackupPath = "\\SHPFS02\IT\EmPower Old";
$EmailFolders = @();

if(-Not(Test-Path -path ($TargetFolder + "\OldFiles" ))) {
    mkdir -p ($TargetFolder +"\OldFiles");    
}
$Network = Test-Path $BackupPath
#New-PSDrive -Name O -PSProvider FileSystem -Root "$BackupPath"; #-Credential $cred

Write-Host "Running Script"
dir $TargetFolder | %{

    # Only delete files with the Email prefix
    $name = $_.Name;    
    if ($_.Name.Length -le 5) {return;}
    $id = $_.Name.SubString(0,5);            
    if ($id -eq "Email")
    {       
        Write-Host "Found slip folder"        
        $EmailFolders += $TargetFolder + $_;        
    }
}

ForEach ($folder in $EmailFolders)
{
    Write-Host $folder;
    dir -path $folder -include *.pdf | %{

        Write-Host "Checking" $name;
        # Only select files older than 6 months
        if( $_.LastWriteTime -le "$LastWrite")
        {
            $activeItem = Get-Item $TargetFolder + $_;
            #Move files into oldfiles
            Write-Host $TargetFolder
            move-item -path $activeItem -destination ($TargetFolder + "OldFiles\");            
            if ($Network)
            {                
                move-item -path $activeItem  -destination "O:\";
            }            
            Write-Host $_;            
            remove-item $activeItem;
            Write-Host "Deleting" + $name;
        }
    }
}

该脚本一直工作到第 31 行,但在第 32 行之后没有继续,作为一个相当初级的 PS 用户,我不明白为什么。

4

1 回答 1

2

-include-recurse参数一起使用。

http://technet.microsoft.com/en-us/library/hh849800.aspx

Include 参数仅在命令包含 Recurse 参数或路径指向目录的内容时才有效,例如 C:\Windows*,其中通配符指定 C:\Windows 目录的内容。

你想要的是-filter参数:

dir -path $folder -filter *.pdf
于 2013-07-30T02:02:00.043 回答