【问题标题】:Zipping folders in powershell在 powershell 中压缩文件夹
【发布时间】:2017-11-03 01:03:35
【问题描述】:

希望其他脚本编写者可以帮助解决这个问题 :) 几个小时以来我一直在思考这个问题。

我正在尝试使用 powershell 压缩某些文件夹。 我的文件夹结构是

备份
BoxIntranet
组件
内容
数据库
执行
文件
日志
多浏览器
多浏览器\旧版\定制

家长门户
父门户\自定义
学生门户
学生门户\定制
更新
WebDav

在上述每一个中都有更多的文件和文件夹,但这些是我主要感兴趣的。 我正在尝试使用 PowerShell 中的 Write-Zip 或 Compress-Archive 方法将其全部压缩,但我的条件是。

  1. 只能从根目录压缩内容、文件、数据库文件夹

  2. Multibrowser\Legacy\customisation、StudentPortal\Customisation 和 ParentPortal\customisation 文件夹也应该备份。

  3. zip 文件中的文件夹结构应保持不变,这意味着 zip 文件的根目录应具有 Content、Files、Database、Multibrowser、ParentPortal 和 StudentPortal 文件夹。虽然 Content、Files 和 Database 文件夹应该包含所有内容,但 Multibrowser、ParentPortal 和 StudentPortal 文件夹应该只包含指定的子目录和其中的所有文件。

代码:

$FilesAndInclude = @("Content", "Files", "Database", "Multibrowser\Legacy\customisation", 
                     "StudentPortal\customisation", "ParentPortal\customisation", 
                     "BoxIntranet\customisation")
$FilesToExclude = @("connectionstrings.config", "inc_dbconn.asp")
Get-ChildItem -Path "C:\Folder" -Include $FilesAndInclude -Recurse -Exclude $FilesToExclude|
    Compress-Archive -DestinationPath "Archive.zip"

我已经尝试了上述方法,但它没有做任何事情,但是如果我删除 -Include 参数,那么它会压缩所有内容,但不会保留文件夹结构。

有什么方法可以在 powershell 中完成我所追求的吗?

【问题讨论】:

  • “什么都不做”是什么意思?是否有一条或多条错误消息?是否创建了 Archive.zip 文件? Get-ChildItem 的输出是你期望的文件名和目录名吗?

标签: powershell zip


【解决方案1】:

好的,首先,您很难使用-Include 参数的原因是因为它被设计为仅包含您指定的内容。因此,它将查看事物的名称(而不是它们的路径),并检查列表,如果它与列表中的某些内容匹配,它将包含该项目。由于您只列出文件夹名称,因此它只包括那些文件夹(但不包括它们的内容)。因此,您不会以这种方式通过管道传递任何文件。要解决这个问题,您需要先构建文件列表,然后将其传送到 cmdlet 以压缩文件。

下一个问题是Compress-Archive 不存储路径信息,因此您需要使用Write-Zip。我已经包含了我认为你想要的那个 cmdlet 的内容。

$FilesAndInclude = @("Content", "Files", "Database", "Multibrowser\Legacy\customisation", 
                     "StudentPortal\customisation", "ParentPortal\customisation", 
                     "BoxIntranet\customisation")
$FilesToExclude = @("connectionstrings.config", "inc_dbconn.asp")
[array]$FilesToZip = Get-ChildItem .\* -Exclude $FilesToExclude -File
$FilesToZip += $FilesAndInclude | ForEach{Get-ChildItem .\$_ -Exclude $FilesToExclude -File}
$FilesToZip | Write-Zip -EntryPathRoot $(Resolve-Path .\|Select -Expand Path) -OutputPath Archive.zip

【讨论】:

  • 你是明星。这段代码并没有完全符合我的要求,但它确实给了我一个很好的起点。这为我完成了工作:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 2014-06-12
  • 2023-03-22
  • 1970-01-01
  • 2010-09-05
  • 2021-09-13
相关资源
最近更新 更多