PowerShell压缩 - 归档文件扩展名

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

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

Directory1
    Config1.config
Directory2
    Config2.config

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

powershell zip powershell-v5.0
1个回答
2
投票

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

$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
}
© www.soinside.com 2019 - 2024. All rights reserved.