【问题标题】:Only copy certain file types after unzipping解压后仅复制某些文件类型
【发布时间】:2015-07-01 22:13:17
【问题描述】:

我有以下代码来解压缩目录树中的许多文件夹:

new-Item E:\Files -type directory

Get-Childitem -path E:\SNL_Insurance\* -recurse -exclude "*.md5" |

Foreach-object {

    $file = $_
    write-host $file;
    $destination = "E:\Files"
    $shell = new-object -com shell.application
    $zip = $shell.NameSpace($file.Fullname) 

    foreach($item in $zip.items()){

        if ($item.name -eq ".txt") {
            $shell.Namespace($destination).copyhere($item)
        }
    }

}

如果没有 if 语句,脚本也会复制 zip 文件,而不仅仅是下面包含的文本文件。我想我可以检查以确保文件扩展名是 .txt (或 *.txt 我都试过了),但 $item.name 似乎不包含我认为的内容。如果您有任何想法和/或可以在此处解释 $shell 变量(特别是 $shell.Namespace 这将非常有帮助),请提前致谢。

编辑:感谢您的回复。在我看到这些答案之前,我实际上找到了另一种方法。如果有人感兴趣,这是我找到的解决方案:

new-Item E:\Files -type directory

Get-Childitem -path E:\SNL_Insurance\Insurance\* -recurse -exclude "*.md5"|

Foreach-object {

    if ($_.extension -eq ".zip") {
        Get-Childitem -path $_ -recurse| 

            Foreach-object {

                    $file = $_
                    write-host $file;
                    $destination = "E:\Files"
                    $shell = new-object -com shell.application
                    $zip = $shell.NameSpace($file.Fullname) 

                    foreach($item in $zip.items()){

                        $shell.Namespace($destination).copyhere($item)

                    }

            }       


    }
}

【问题讨论】:

  • 您可能正在寻找$item.extension
  • @RyanBemrose FolderItem 对象没有这样的属性。

标签: powershell


【解决方案1】:

仅复制您可以使用的文本文件:

foreach($item in $zip.items()){
if ($item.Type -eq 'Text Document') {
        $shell.Namespace($destination).copyhere($item)
    }
}

或

$zip.items() | Where-Object {$_.Type -eq 'Text Document'} | 
    Foreach-Object { $shell.NameSpace($Destination).copyhere($_)}

我怎么知道使用type 属性?我用过:

$zip.items()

查看所有可用的属性。

【讨论】:

  • 只看documentation 可能更简单。 ;)
  • 他说的是真的 :) ...MSDN 上有很多很好的信息,但我们不经常查看...thx @AnsgarWiechers
【解决方案2】:

Items() 方法枚举FolderItem 对象,这些对象(与FileInfo 对象不同)没有Extension 属性。您可以使用-like 运算符进行通配符匹配:

foreach ($item in $zip.Items()) {
    if ($item.Name -like '*.txt') {
        $shell.NameSpace($destination).copyhere($item)
    }
}

或(如@Kiran 建议的那样)检查对象的类型:

foreach ($item in $zip.Items()) {
    if ($item.Type -eq 'text document') {
        $shell.NameSpace($destination).copyhere($item)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2019-10-31
    • 2010-12-18
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    相关资源
    最近更新 更多