【问题标题】:Archive folders only when the folder has certain file types仅当文件夹具有某些文件类型时才归档文件夹
【发布时间】:2016-06-07 18:43:29
【问题描述】:

仅当文件夹具有特定类型的文件(例如 .txt.csv.xls.xlsx)时,如何编写 PowerShell 脚本来归档文件夹。我的源路径是C:\Temp\Test\,有5个子文件夹:

  • 文件夹
  • 文件夹b
  • 文件夹c
  • 文件夹
  • 文件夹
  • 存档

只有folderafolderbfolderc 有要归档的文件,归档路径是C:\Temp\Test\Archive,这里有folders folderafolderb,所以这些文件夹不需要创建,但是需要压缩和复制文件,需要创建folderc并且需要压缩和复制文件。

使用下面的代码,我得到了文件,但没有得到特定文件所在的文件夹。

    $ignorefolders = @(
    "C:\Temp\misc"   
    )

$archive = "C:\Temp\Archive" 

[regex]$exclude = ‘(?i)^(‘ + (($ignorefolders |foreach {[regex]::escape($_)}) –join “|”) + ‘)’

$includefiletype = @("*.txt", "*.csv", "*.dat", "*.xls", "*.xlsx")     
$workingDir = "C:\Temp"

Get-ChildItem $workingDir -recurse -include $fileFilter | Where {$_.FullName -notmatch $exclude} | Copy-Item -Destination $archive

【问题讨论】:

    标签: powershell


    【解决方案1】:

    要获取目录,请选择从 Get-ChildItem 返回的 FileInfo 对象的 Directory 属性,我还假设您不想要任何重复项,因此,您必须使用 @ 过滤掉那些987654323@:

    Get-ChildItem -Recurse -Path $source -include*.txt,*.csv,*.xls,*.xlsx | select directory | sort -Unique -Property Directory | Select -expand Directory | Copy-Item -Destination $archive -WhatIf
    

    【讨论】:

    • 我收到“Copy-Item 找不到驱动器”错误,Copy-Item 不应该指定源路径。当我将 Copy-Item 更改为“Copy-Item -Path $source -Destination $archive -WhatIf”时,出现参数绑定错误。
    • 看来 Copy-Item 不喜欢 FileInfo 对象作为输入,所以在将属性发送到 Copy-Item 之前进行了编辑以扩展该属性,但是,我感觉还是不行做你想做的事。您可能想向 Copy-Item 添加 -Recurse 参数。
    • 我可以使用以下脚本过滤文件和文件夹。但是,它只复制文件夹,所有文件都复制到外面。如何复制包含文件的文件夹。
    • 用修改后的powershell脚本更新了原帖。
    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    相关资源
    最近更新 更多