我正试图编写一个解压的powershell脚本,但我遇到了$shell.NameSpace()
函数的问题。
function unzip ($sourceFile, $destination){
$shell = new-object -com shell.application
$zip = $shell.NameSpace($sourceFile)
foreach($item in $zip.items()){
$shell.Namespace($destination).copyhere($item) #Error here
}
}
unzip "$PWDfolder.zip" $PWD
当我运行这个程序时,我在第二个$shell.NameSpace()
调用中得到一个错误。
You cannot call a method on a null-valued expression.
At C:scriptDirunzipScript.ps1:9 char:6
+ $shell.NameSpace($destination).copyhere($item)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : InvokeMethodOnNull
我不明白的是,为什么这在第二次调用时失败。显然,PWD
是存在的,并且是基于第一个参数的目录。
Shell.NameSpace接受一个字符串$PWD是一个PathInfo对象。您可以改用$pwd.Path。
unzip "$PWDfolder.zip" $PWD.Path
也可以使用.Net System.IO.Compression.ZipFile类。这是一个样品。