【问题标题】:Powershell Zip Directory exclude some SubdirectoriesPowershell Zip 目录排除一些子目录
【发布时间】:2017-12-06 15:09:21
【问题描述】:

我正在编写一个 powershell 脚本,我想在其中 .zip 一个包含 2 个子目录的目录。在其中一个子目录中,我想排除另一个目录。

myDirectory
-- sub 1
--- sub 1.1
--- sub 1.2
-- sub 2
--- sub 2.1
--- sub 2.2

我编写了这个脚本,但它不起作用。谁能给我一个提示或告诉我我做错了什么?

$ChildItemPath = "myDirectory"

$Date = [DateTime]::Now.ToString("yyyyMMdd-HHmmss")
$Exclude = @("myDirectory/sub 2/sub 2.1")

$DestinationPath = "Archive-v" + $Date

$CompressPath = Get-ChildItem -Path $ChildItemPath -Exclude $Exclude

Compress-Archive -Path $CompressPath -DestinationPath $DestinationPath -update

.bat/.ps1 文件与“myDirectory”位于同一目录中

-------------- 编辑 19:55 ----- --------- 当子文件夹非常“小”时,Reza 建议的解决方案可以正常工作。我正在尝试从 AngularClient-dir 中排除“node_modules”。

所以最终的 .zip 文件包含一个 'serverside'-dir: vs217 asp.net core project 和一个没有 node_modules 的 'clientside'-dir: angular4 项目

【问题讨论】:

  • -Exclude 仅适用于 -Recurse* 参数中的 * 通配符。
  • 你的意思是,这不能做?
  • 这意味着您需要使用这两种方法之一才能完成。
  • @user7049371 您可以在以下位置找到可能的解决方案:stackoverflow.com/a/59018865/2349693

标签: powershell zip node-modules subdirectory


【解决方案1】:

要在创建 zip 文件时排除文件夹的某些子文件夹,作为一个选项,您可以将排除这些子文件夹的文件夹复制到 windows 临时目录中的临时文件夹。然后压缩临时文件夹:

$inputFolder = "C:\MyDirectory"
$excludeFolders = @("\Sub1\Sub1-2", "\Sub2\Sub2-2")
$ouputFileName="C:\MyFile.zip"

$tempFolder = [System.IO.Path]::GetTempFileName()
Remove-Item $tempFolder -Force
New-Item -Type  Directory -Path $tempFolder -Force
$exclude =@()
$excludeFolders | ForEach-Object {
 $exclude+=(Join-Path $inputFolder $_) 
 Get-ChildItem (Join-Path $inputFolder $_) -Recurse | 
  ForEach-Object{$exclude+=$_.FullName}}
Get-ChildItem $inputFolder -Recurse | Where-Object { $_.FullName -notin $exclude} |
 Copy-Item -Destination {Join-Path $tempFolder $_.FullName.Substring($inputFolder.length)}

Get-ChildItem $tempFolder |
Compress-Archive -DestinationPath $ouputFileName -Update
# Remove-Item $tempFolder -Force -Recurse

【讨论】:

  • 不幸的是,这需要一段时间,因为我试图排除一个 'node_modules'-dir... 这不是时间。
  • 我让它更快了。您还可以评论最后一个删除命令,并让 Windows 在需要空间时删除文件夹。删除命令也需要一些时间。
  • 注意,我更新了脚本。更新不仅仅是评论最后一行。我还更改了将文件复制到临时目录的方式。以前,我也是复制排除的文件然后删除它们,但现在我不复制它们了。
  • 嗨 Reza,我刚刚尝试了您编辑的脚本,但脚本仍然没有运行 5 分钟,还没有完成……我将在新回复中发布详细信息
猜你喜欢
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多