繁体   English   中英

如何使用 PowerShell 文件 Zip 文件(没有 PS 版本 5 或 .NET 框架 4.5)

[英]How to Zip Files using PowerShell (without PS Version 5 or .NET Framework 4.5)

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

由于这些系统的年代久远,我无法使用Compress-ArchiveSystem.IO.Compression.FileSystem 除了实际的压缩 function 之外,我已经完成了整个脚本。 所有其他在线解决方案都告诉我使用 .NET 4.5 方式或 powershell V5 方式,这在我正在使用的系统上是不可能的。 有任何想法吗?

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

您可以使用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(".\Desktop\zip.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:\Users\Ash\Desktop\test") # Specify full path

# Path to zip file created earlier
$out = $sa.NameSpace("C:\Users\Ash\Desktop\zip.zip") # Specify full path

# Copy files in to archive.
$out.CopyHere($in.Items(), 4) # 4 = No Progress Box

Folder.CopyHere

每个人都喜欢可重复使用的 function 并且能够使用相对路径...

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 .\Desktop\test\ -Output .\Desktop\zip.zip

或者

Get-Item .\Desktop\test\ | ConvertTo-Archive -Output .\Desktop\zip.zip

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM