如何解压多个文件?

3
我正在尝试循环遍历文件夹中的zip文件并将它们解压缩。当我调用 zip.items() 时,出现了null错误。可能是什么原因导致这个值为null?
当我使用 Write-Host $zip 时,输出的值是System.__ComObject
$dira = "D:\User1\Desktop\ZipTest\IN"
$dirb = "D:\User1\Desktop\ZipTest\DONE\" 

$list = Get-childitem -recurse $dira -include *.zip

$shell = new-object -com shell.application

foreach($file in $list)
{
    $zip = $shell.NameSpace($file)
    foreach($item in $zip.items())
    {
        $shell.Namespace($dirb).copyhere($file)
    }
    Remove-Item $file
}

我收到的错误信息是:
You cannot call a method on a null-valued expression.  
At D:\Users\lr24\Desktop\powershellunziptest2.ps1:12 char:29  
+     foreach($item in $zip.items <<<< ())
    + CategoryInfo          : InvalidOperation: (items:String) [], RuntimeException  
    + FullyQualifiedErrorId : InvokeMethodOnNull

请展示您正在运行的实际代码(不是您捏造或从记忆中输入的内容),以及您收到的完整错误信息。 - Ansgar Wiechers
我已经更新了问题。谢谢。 - cchristie45
3个回答

3

$file 是一个 FileInfo 对象,但是 NameSpace() 方法需要一个带有完整路径的字符串或者一个数字常量。此外,请复制 $item 而不是 $file

请将这样更改:

foreach($file in $list)
{
    $zip = $shell.NameSpace(<b>$file</b>)
    foreach($item in $zip.items())
    {
        $shell.Namespace($dirb).copyhere(<b>$file</b>)
    }
    Remove-Item $file
}

转化为这样:

foreach($file in $list)
{
    $zip = $shell.NameSpace(<b>$file.FullName</b>)
    foreach($item in $zip.items())
    {
        $shell.Namespace($dirb).copyhere(<b>$item</b>)
    }
    Remove-Item $file
}

谢谢。我注意到没有使用全名,并且几分钟前找到了一个解决方案,使用get-childitem命令中的全名。 - cchristie45

2
如果您的$env:path中有7-zip
PS> $zips = dir *.zip
PS> $zips | %{7z x $_.FullName}

#unzip with Divider printed between unzip commands
PS> $zips | %{echo "`n`n======" $_.FullName; 7z x $_.FullName}

您可以在此处获取7-zip:

http://www.7-zip.org/

PS> $env:path += ";C:\\Program Files\\7-Zip"

解释:

百分号后跟花括号被称为foreach运算符:%{ } 这个运算符的意思是,在管道中的“Foreach”对象,花括号中的代码将使用该对象放置在“$ _”变量中进行调用。


-1

你缺少了shell初始化。

$shell = new-object -com shell.application

在命名空间之前使用它。


我上面的帖子中遗漏了它,但是它在我的代码中,我仍然收到错误。 - cchristie45
尝试在for循环中使用$zip[i],而不是$zip.items() - Pramuka
我尝试了一下,但返回了“数组索引表达式无效或缺失。位于第10行第24个位置。” - cchristie45

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接