我有一个powershell脚本,它接收目录中的文件夹列表,并压缩最新的.bak文件并将其复制到另一个目录中。
有两个文件夹我不希望它查找.bak文件。如何排除这些文件夹?我尝试过多种方式的-Exclude语句,但我没有任何运气。
我想忽略的文件夹是“新建文件夹”和“新folder1”
$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"
}谢谢!
发布于 2017-04-21 22:59:15
我要做的是在找到的文件上使用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
}或者,如果您只想提供一个文件夹列表来排除,您可以对directoryName属性执行一些字符串操作,只获取最后一个文件夹,并查看它是否位于一个排除类列表中:
$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
}https://stackoverflow.com/questions/43552890
复制相似问题