使用Powershell解压缩受密码保护的文件

问题描述

PowerShell密码保护的文件 嗨,我是Powershell的新手,并尝试学习一些技巧。 我创建了一个简单的代码,应该使用7zip和一个已知的密码来解压缩文件

这是代码

$7ZipPath = '"C:\Program Files\7-Zip\7z.exe"'
$zipFile = '"C:\Users\touff\OneDrive\Bureau\0\Encrypted Zip\test.zip"'
$path = 'C:\Users\touff\OneDrive\Bureau\0\Encrypted Zip\foldertest'


New-Item -ItemType directory -Path $path
Read-Host -Prompt 'step1'

$password = Read-Host -Prompt 'Input the password'
Write-Host $password
$command = "& $7ZipPath e -oC:\ -y -tzip -p$password $zipFile"
Invoke-Expression $command

我一直遇到这些错误

  • 7-Zip [64] 16.04:版权所有(c)1999-2016 Igor Pavlov:2016-10-04

  • 扫描驱动器中的存档:

  • 1个文件,310字节(1 KiB)

  • 提取档案:C:\ Users \ touff \ OneDrive \ Bureau \ 0 \ Encrypted Zip \ test.zip

  • 路径 = C:\ Users \ touff \ OneDrive \ Bureau \ 0 \ Encrypted Zip \ test.zip

  • 类型= zip

  • 物理尺寸= 310

  • 错误:无法打开输出文件:拒绝。 : C:\ ok.t​​xt

  • 子项错误:1

  • 归档错误:1

  • 子项错误:1

解决方法

这就是您要在函数形式中进行的工作,以对其进行一些清理

Function Open-7ZipFile{
    Param(
        [Parameter(Mandatory=$true)]
        [string]$Source,[Parameter(Mandatory=$true)]
        [string]$Destination,[string]$Password,[Parameter(Mandatory=$true)]
        [string]$ExePath7Zip,[switch]$Silent
    )
    $Command = "& `"$ExePath7Zip`" e -o`"$Destination`" -y" + $(if($Password.Length -gt 0){" -p`"$Password`""}) + " `"$Source`""
    If($Silent){
        Invoke-Expression $Command | out-null
    }else{
        "$Command"
        Invoke-Expression $Command
    }
}

这是运行方法

Open-7ZipFile -ExePath7Zip "C:\Program Files\7-Zip\7z.exe" -Source "C:\Users\touff\OneDrive\Bureau\0\Encrypted Zip\test.zip" -Destination "C:\Users\touff\OneDrive\Bureau\0\Encrypted Zip\foldertest" -Password "Password"

确保您有权访问要解压缩到的文件夹

如果您没有权限,则会遇到您现在得到的错误

错误:无法打开输出文件:拒绝。 :C:\ ok.t​​xt

编辑了该功能以允许空格并以静默方式运行。

,

您不需要Invoke-Expression;只需使用所需参数运行命令。这是您可以使用的简短示例脚本(可以根据需要进行修改):

param(
  [Parameter(Mandatory = $true)]
  [String]
  $ArchiveFilename,[String]
  $DestinationPath,[Switch]
  $HasPassword
)

$ARCHIVE_TOOL = "C:\Program Files\7-Zip\7z.exe"

function ConvertTo-String {
  param(
    [Security.SecureString] $secureString
  )
  try {
    $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
    [Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
  }
  finally {
    if ( $bstr -ne [IntPtr]::Zero ) {
      [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
    }
  }
}

if ( $HasPassword ) {
  $securePwd = Read-Host -AsSecureString -Prompt "Enter archive password"
  if ( $securePwd ) {
    $password = ConvertTo-String $securePwd
  }
}

if ( -not $DestinationPath ) {
  $DestinationPath = (Get-Location).Path
}

& $ARCHIVE_TOOL e "-o$DestinationPath" "-p$password" $ArchiveFilename

如果脚本名为Expand-ArchiveFile.ps1,请按以下方式运行它:

Expand-ArchiveFile.ps1 "C:\Users\touff\OneDrive\Bureau\0\Encrypted Zip\test.zip" -HasPassword

请注意,在指定文件名时,不需要嵌入的引号。 (引号不是文件名的一部分。)