【问题标题】:Powershell folder archivingPowershell 文件夹归档
【发布时间】:2020-04-12 05:03:16
【问题描述】:

我有一个 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


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 谢谢!!解决了我的问题。我所做的唯一更改是 $directory 的目标路径,这样它将 zip 放在子文件夹本身中
    【解决方案2】:

    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

    【讨论】:

      【解决方案3】:

      你可以这样做:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        • 1970-01-01
        • 2018-12-03
        • 1970-01-01
        相关资源
        最近更新 更多