Powershell 文件夹存档



我有一个Powershell脚本,它只是使用Get-ChildItem命令在目录中搜索与关键字匹配的文件夹。 找到后,我需要它来压缩它并将其保留在同一目录中。

以下是我通过将命令管道到 7zip 和本机压缩中尝试的方法:

set-alias zip "$env:ProgramFiles7-Zip7z.exe"
Get-ChildItem $path "keyword" -Recurse -Directory | zip a
AND
Get-ChildItem $path"keyword" -Recurse -Directory | compress-archive

两次它总是要求源和目标,这很难定义,因为我让它搜索具有许多子文件夹的驱动器。 我虽然使用管道也会暗示来源。

有什么想法吗? 谢谢!

编辑:

我想我可以将 Get-ChildItem 设置为一个变量并将其用作"源",并使目标成为它们的通用位置,但我必须以不同的方式命名它们,不是吗?

试一试:

$path = "INSERT SOURCE ROOT"
foreach ($directory in Get-ChildItem $path -Recurse -Directory -Filter "keyword"| Select-Object FullName | foreach { $_.FullName}) {
$destination = Split-Path -Path $directory -Parent
Compress-Archive -Path $directory -DestinationPath $destination
}

这是在路径内部查找与"关键字"匹配的任何内容,向上 1 级,然后压缩找到的文件。

C:下有temptemp2目录,这对我有用(请注意,目录必须包含内容(:

Get-ChildItem "C:" "temp*" -directory | compress-archive -DestinationPath "C:tempzip.zip"

它压缩找到的所有目录以C:tempzip.zip

我相信你真正想要的是:

$dirs = Get-ChildItem "C:" "temp*" -directory
foreach ($dir in $dirs){
compress-archive $dir.fullname -DestinationPath "$($dir.fullname).zip"
}

请注意,我在测试中省略了-recurse

你可以这样做:

get-childitem -path "The Source Path" -recurse | where {$_.Name -match "Keyword"} | foreach {
$parent = Split-Path -Path $_ -Parent
Compress-Archive -Path $_ -DestinationPath $parent
}

最新更新