Powershell密码保护文件嗨,我是Powershell的新手,试着学习一些技巧。我创建了一个简单的代码,应该使用7zip和已知密码来解压缩文件。
这是代码:
$7ZipPath = '"C:Program Files7-Zip7z.exe"'
$zipFile = '"C:UserstouffOneDriveBureau Encrypted Ziptest.zip"'
$path = 'C:UserstouffOneDriveBureau Encrypted Zipfoldertest'
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\加密的Zip\test.Zip
路径=C:\Users\touff\OneDrive \ Bureau\0\加密Zip\test.Zip
类型=zip
物理尺寸=310
错误:无法打开输出文件:Accès refusé。:C: \ok.txt
子项错误: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 Files7-Zip7z.exe" -Source "C:UserstouffOneDriveBureau Encrypted Ziptest.zip" -Destination "C:UserstouffOneDriveBureau Encrypted Zipfoldertest" -Password "Password"
确保您有权访问要解压缩到的文件夹
如果你没有权利,你会得到错误你现在
错误:无法打开输出文件:Accès refusé。:C: \ok.txt
编辑了函数以允许空间并以静默方式运行
您不需要Invoke-Expression
;只需使用所需的参数运行命令即可。以下是您可以使用的简短示例脚本(根据需要进行修改(:
param(
[Parameter(Mandatory = $true)]
[String]
$ArchiveFilename,
[String]
$DestinationPath,
[Switch]
$HasPassword
)
$ARCHIVE_TOOL = "C:Program Files7-Zip7z.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:UserstouffOneDriveBureau Encrypted Ziptest.zip" -HasPassword
请注意,在指定文件名时,不需要嵌入引号。(引号不是文件名的一部分。(