PowerShell 按文件扩展名压缩归档 [英] PowerShell Compress-Archive By File Extension

查看:27
本文介绍了PowerShell 按文件扩展名压缩归档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I use the PowerShell 5.0 Compress-Archive cmdlet to recursively take any .config files in a directory and zip them up while maintaining the directory structure. Example:

Directory1
    Config1.config
Directory2
    Config2.config

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

The aim is a single zip file also containing the above directory structure and only config files.

推荐答案

我建议将文件复制到临时目录并进行压缩.例如:

I would suggest copying the files to a temporary directory and compress that. Ex:

$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
}

这篇关于PowerShell 按文件扩展名压缩归档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆