【问题标题】:PowerShell Compress-Archive By File ExtensionPowerShell Compress-Archive 按文件扩展名
【发布时间】:2016-07-08 06:24:08
【问题描述】:

如何使用 PowerShell 5.0 Compress-Archive cmdlet 以递归方式获取目录中的任何 .config 文件并将其压缩,同时保持目录结构。示例:

Directory1
    Config1.config
Directory2
    Config2.config

目标是一个包含上述目录结构和仅配置文件的单个 zip 文件。

【问题讨论】:

  • 什么意思?找到一个配置文件,将其压缩(仅配置文件)并将压缩文件保留在与配置文件相同的位置?
  • 我添加了一个插图。
  • 文件结构是唯一明确的部分。期望的输出是什么样的?您想要一个包含所有配置文件的 zip 文件吗?还是每个配置文件一个 zip 文件?
  • 具有上述目录结构的单个 zip。

标签: powershell zip powershell-5.0


【解决方案1】:

我建议将文件复制到一个临时目录并压缩它。例如:

$path = "test"
$filter = "*.config"

#To support both absolute and relative paths..
$pathitem = Get-Item -Path $path

#If sourcepath exists
if($pathitem) {
    #Get name for tempfolder
    $tempdir = Join-Path $env:temp "CompressArchiveTemp"

    #Create temp-folder
    New-Item -Path $tempdir -ItemType Directory -Force | Out-Null

    #Copy files
    Copy-Item -Path $pathitem.FullName -Destination $tempdir -Filter $filter -Recurse

    #Get items inside "rootfolder" to avoid that the rootfolde "test" is included.
    $sources = Get-ChildItem -Path (Join-Path $tempdir $pathitem.Name) | Select-Object -ExpandProperty FullName

    #Create zip from tempfolder
    Compress-Archive -Path $sources -DestinationPath config-files.zip

    #Remove temp-folder
    Remove-Item -Path $tempdir -Force -Recurse
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2019-03-14
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2012-04-05
    相关资源
    最近更新 更多