Powershell文件夹归档

问题描述 投票:0回答:2

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

这是我通过将命令传递到7zip和本机压缩文件中所尝试的:

    set-alias zip "$env:ProgramFiles\7-Zip\7z.exe"
    Get-ChildItem $path "keyword" -Recurse -Directory | zip a
AND
    Get-ChildItem $path"keyword" -Recurse -Directory | compress-archive

两次,它总是要求提供一个很难定义的源和目标,因为我要通过一个带有许多子文件夹的驱动器进行搜索。我虽然使用管道也会暗示源。

有什么想法吗?谢谢!

编辑:

我想我可以将Get-ChildItem设置为一个变量,并将其用作“源”,并让目的地成为所有对象的通用位置,但我必须以不同的方式命名它们,不是吗?

powershell archive 7zip
2个回答
0
投票

尝试一下:

$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级,然后压缩找到的文件。


0
投票

[在temp下有temp2C:\目录,这对我有用(请注意目录必须包含内容):

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

© www.soinside.com 2019 - 2024. All rights reserved.