Powershell 文件夹归档

Powershell folder archiving

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

以下是我尝试将命令传送到 7zip 和本机压缩包中的方法:

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

两次它总是要求提供一个很难定义的源和目标,因为我让它搜索具有许多子文件夹的驱动器。我虽然使用管道也意味着来源。

有什么想法吗?谢谢!

编辑:

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

试一试:

$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

}

这是在路径中查找与 "keyword" 匹配的任何内容,向上一级,然后压缩找到的文件。

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
}