我正在编写一个脚本来删除带有“电子邮件”前缀的文件夹中超过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用户,我看不出原因。
答案 0 :(得分:2)
仅将-include
与-recurse
参数一起使用。
http://technet.microsoft.com/en-us/library/hh849800.aspx
Include参数仅在命令包含时有效 Recurse参数或路径指向目录的内容, 例如C:\ Windows *,其中通配符指定了 C:\ Windows目录的内容。
您想要的是-filter
参数:
dir -path $folder -filter *.pdf