powershell 如何解压缩多个文件?

svmlkihl  于 2023-02-08  发布在  Shell
关注(0)|答案(3)|浏览(277)

我正在尝试遍历文件夹中的zip文件并解压缩它们。我收到了zip.items()的空错误。这个值怎么会是空的呢?
当I 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
dz6r00yl

dz6r00yl1#

$fileFileInfo对象,但NameSpace()方法需要具有完整路径的字符串或数字常量。此外,您需要复制$item,而不是$file
更改此内容:

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

变成这样:

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

kq4fsx7k2#

如果$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"

说明:
后面跟大括号的percent称为foreach运算符:%{}此运算符表示管道中的"Foreach"对象,调用大括号中的代码时将对象放在"$_"变量中。

n3h0vuf2

n3h0vuf23#

你错过了shell初始化。

$shell = new-object -com shell.application

在命名空间之前使用它。

相关问题