首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell -列出目录中的所有文件夹,在每个文件夹中拉出最新的.bak文件,将其压缩,复制到目录中。

Powershell -列出目录中的所有文件夹,在每个文件夹中拉出最新的.bak文件,将其压缩,复制到目录中。
EN

Stack Overflow用户
提问于 2017-04-21 22:25:08
回答 1查看 377关注 0票数 0

我有一个powershell脚本,它接收目录中的文件夹列表,并压缩最新的.bak文件并将其复制到另一个目录中。

有两个文件夹我不希望它查找.bak文件。如何排除这些文件夹?我尝试过多种方式的-Exclude语句,但我没有任何运气。

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

代码语言:javascript
复制
$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"
}

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-21 22:59:15

我要做的是在找到的文件上使用Directory属性,并使用-NotLike操作符对不想要的文件夹进行简单匹配。我还将使用通配符简化搜索:

代码语言:javascript
复制
$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属性执行一些字符串操作,只获取最后一个文件夹,并查看它是否位于一个排除类列表中:

代码语言:javascript
复制
$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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43552890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档