我需要包括空目录沿着与一个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
21032;的东西,非常奇怪。我又试了一次,我发誓它对我不起作用。如果我给它给予空目录的名称,它甚至不会创建一个zip文件。我打算重新安装Windows,只要我的新SSD到达,也许这修复它。
顺便说一句,我需要这个WordPress插件开发,因为你必须上传一个zip文件的插件。我上传了我用这个脚本创建的存档,它产生了一个非常奇怪的结果。而不是正确地解压缩的zip,因为WordPress已经做了每一次之前,它所做的是这样的:
some\file\which\should\be\in\a\directory.php
weird\file\again.php
normal.php
不,那些不是**路径,它们是文件名。在Windows上,我可以很好地解压缩它。我很困惑。
1条答案
按热度按时间hgb9j2n61#
注意:
在创建或更新存档文件时,Compress-Archive小工具将忽略隐藏的文件和文件夹。
如果您的目录只包含隐藏文件,则可能显示为空(if you haven't told File Explorer to show hidden files)。那么当你使用
Compress-Archive
时,由于这种行为,它将实际上是空的。医生们接着说:
若要确保隐藏的文件和文件夹被压缩到存档中,请改用.NET API。
这似乎是fixed in 2.0.0,但在撰写本文时,自2022年8月以来一直是stuck as a preview release。