如何使用PowerShell压缩文件(没有PS V5或.NET Framework 4.5)



我正在寻找一种使用 Powershell 创建新的 ZIP 存档或将文件添加到现有存档的方法。此脚本将在非常旧的系统上运行,其中一些系统仍在使用 Powershell 版本 2 和 .NET Framework 3.0 或更早版本。没有任何升级的可能性,因为它们是未连接到互联网的客户端生产系统,并且我无法安装任何附加组件或扩展。

由于这些系统的年龄,我无法使用Compress-ArchiveSystem.IO.Compression.FileSystem。除了实际的压缩功能外,我还有完整的整个脚本。所有其他在线解决方案都告诉我要么使用 .NET 4.5 方式,要么使用 Powershell V5 方式,这在我正在使用的系统上是不可能的。有什么想法吗?

这是我的代码的链接:https://pastebin.com/m8FjFhcr 第 #113 行是 zip 命令所在的位置。

您可以使用Shell.Application.

# Create an empty zip file
$byte = @([byte]80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
[System.IO.File]::WriteAllBytes(".Desktopzip.zip", $byte)
# New Shell.Application ComObject
$sa = New-Object -ComObject Shell.Application
# Path to folder containing items you wish to zip
$in = $sa.NameSpace("C:UsersAshDesktoptest") # Specify full path
# Path to zip file created earlier
$out = $sa.NameSpace("C:UsersAshDesktopzip.zip") # Specify full path
# Copy files in to archive.
$out.CopyHere($in.Items(), 4) # 4 = No Progress Box

文件夹.复制这里

每个人都喜欢可重用的函数并能够使用相对路径......

function ConvertTo-Archive {
Param(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[Alias("FullName")]
[ValidateScript({Test-Path $_})]
[string]$Path,
[parameter(Mandatory=$true)]
[string]$Output
)
# Convert relative path if one has been used.
$Source = [System.IO.Path]::GetFullPath($Path)
$Destination = [System.IO.Path]::GetFullPath($Output)
$byte = @([byte]80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
[System.IO.File]::WriteAllBytes($Destination, $byte)
$sa = New-Object -ComObject Shell.Application
$in = $sa.NameSpace($Source)
$out = $sa.NameSpace($Destination)
$out.CopyHere($in.Items(), 4)
}

用法

ConvertTo-Archive -Path .Desktoptest -Output .Desktopzip.zip

Get-Item .Desktoptest | ConvertTo-Archive -Output .Desktopzip.zip

最新更新