【发布时间】:2021-03-18 21:04:29
【问题描述】:
我需要在 zip 文件中包含空目录和文件。我可以使用 7-Zip 手动完成这项工作,但我想自动化它,因为我经常这样做。我最近开始学习 powershell,所以我决定试一试。
我的问题是Compress-Archive 自动丢弃空目录。我的解决方法是($Files 是脚本的参数):
$items = Get-ChildItem -Path . | Where-Object { $_.Name -in $Files }
$placeholders = @()
foreach ($item in $items) {
if (($item | Get-ChildItem | Measure-Object).Count -eq 0 ) {
$placeholders += (New-Item -Path "$item\.placeholder")
}
}
在脚本的结尾
foreach ($item in $placeholders) {
$item.Delete()
}
这可行,但它并不漂亮,因为它导致占位符文件位于最终的 zip 中。
有没有好办法在powershell中压缩空目录?
编辑整个脚本,底部有版本信息:
[CmdletBinding()]
param (
# Files and folders to compress, comma separated
[Parameter(Mandatory)]
[string[]]
$Files,
# zip file to create
[Parameter(Mandatory)]
[string]
$ZipName
)
if (-not $ZipName.Contains(".zip")) {
$ZipName += ".zip"
}
$items = Get-ChildItem -Path . | Where-Object { $_.Name -in $Files }
$placeholders = @()
foreach ($item in $items) {
if (($item | Get-ChildItem | Measure-Object).Count -eq 0 ) {
$placeholders += (New-Item -Path "$item\.placeholder")
}
}
if ((Get-ChildItem -Path . | Where-Object { $_.Name -eq $ZipName } | Measure-Object).Count -ne 0) {
Remove-Item -Path "$ZipName"
}
$items | Compress-Archive -DestinationPath $ZipName
foreach ($item in $placeholders) {
$item.Delete()
}
# output of Get-Host
# Name : ConsoleHost
# Version : 5.1.19041.610
# InstanceId : c799930e-ea5e-4ec9-9e5d-41d949bf4ee4
# UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
# CurrentCulture : en-GB
# CurrentUICulture : en-GB
# PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
# DebuggerEnabled : True
# IsRunspacePushed : False
# Runspace : System.Management.Automation.Runspaces.LocalRunspace
EDIT2 非常奇怪的东西。再次测试它,我发誓它对我不起作用。如果我给它空目录的名称,它甚至不会创建一个 zip 文件。我将在我的新 ssd 到货后立即重新安装 Windows,也许可以解决它。
顺便说一下,我需要这个用于 Wordpress 插件开发,因为您必须将插件上传到 zip 文件中。我上传了我用这个脚本创建的档案,它产生了一个非常奇怪的结果。而不是像 Wordpress 那样每次都正确解压缩 zip,而是像这样:
some\file\which\should\be\in\a\directory.php
weird\file\again.php
normal.php
不,那些是不是路径,它们是文件名。在 Windows 上,我可以很好地解压缩它。我很困惑。
【问题讨论】:
-
我无法复制。空目录包含在 zip 文件中。你用的是什么版本的PS?可能最好显示您的 Compress-Archive 命令。
-
@DougMaurer 我编辑了这个问题,所以整个脚本和版本信息都在那里
-
通过说
| Where-Object { $_.Name -in $Files },您会自动过滤那些没有“文件”的文件夹,因此这些空文件夹不会被压缩。除非 $Files 实际上包含您要查找的文件夹名称。 -
@santisq 它确实包含目录的名称,请参阅参数说明
标签: powershell compress-archive