2017-04-21 44 views
0

我有一个PowerShell脚本,它可以获取目录中的文件夹列表,并将最新的.bak文件并将其复制到另一个目录中。Powershell - 列出目录中的所有文件夹,拉动每个文件夹中的最新.bak文件,将其压缩,将其复制到目录

有两个文件夹,我不希望它寻找.bak文件。我如何排除这些文件夹?我已经尝试了多种方式的排除陈述,我没有任何运气。

我想忽略的文件夹是“新建文件夹”和“新文件夹1”

$source = "C:\DigiHDBlah" 
$filetype = "bak" 

$list=Get-ChildItem -Path $source -ErrorAction SilentlyContinue 
foreach ($element in $list) { 
$fn = Get-ChildItem "$source\$element\*" -Include "*.$filetype" | sort LastWriteTime | select -last 1 
$bn=(Get-Item $fn).Basename 
$CompressedFile=$bn + ".zip" 
$fn| Compress-Archive -DestinationPath "$source\$element\$bn.zip" 
Copy-Item -path "$source\$element\$CompressedFile" -Destination "C:\DigiHDBlah2" 
} 

谢谢!

回答

1

我会做的就是使用您找到的文件的Directory属性和-NotLike运算符来为不需要的文件夹进行简单匹配。我也通过使用通配符简化搜索:

$Dest = "C:\DigiHDBlah2" 
$files = Get-ChildItem "$source\*\*.$filetype" | Where{$_.Directory -NotLike '*\New Folder' -and $_.Directory -NotLike '*\New Folder1'} | Sort LastWriteTime | Group Directory | ForEach{$_.Group[0]} 
ForEach($file in $Files){ 
    $CompressedFilePath = $File.FullName + ".zip" 
    $file | Compress-Archive -DestinationPath $CompressedFilePath 
    Copy-Item $CompressedFilePath -Dest $Dest 
} 

或者,如果你只想提供的文件夹列表中排除,你可以做的目录名财产一点点的字符串操作只得到了最后一个文件夹,并查看它是否在排除列表中:

$Excludes = @('New Folder','New Folder1') 
$Dest = "C:\DigiHDBlah2" 
$files = Get-ChildItem "$source\*\*.$filetype" | Where{$_.DirectoryName.Split('\')[-1] -NotIn $Excludes} | Sort LastWriteTime | Group Directory | ForEach{$_.Group[0]} 
ForEach($file in $Files){ 
    $CompressedFilePath = $File.FullName + ".zip" 
    $file | Compress-Archive -DestinationPath $CompressedFilePath 
    Copy-Item $CompressedFilePath -Dest $Dest 
} 
相关问题