【问题标题】:powershell script - create zip file excluding some files and folderspowershell 脚本 - 创建 zip 文件,不包括某些文件和文件夹
【发布时间】:2012-09-18 06:21:59
【问题描述】:

我正在尝试创建 powershell 脚本函数来压缩文件夹,不包括一些文件夹和文件这里是我的代码,它创建包括所有文件和文件夹的 zip 文件

# Zip creator method

function create-zip([String] $aDirectory, [String] $aZipfile){
    [string]$pathToZipExe = "C:\Program Files\7-zip\7z.exe";
    [Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory";
    & $pathToZipExe $arguments;
}

但我想排除 *.tmp 文件以及 bin 和 obj 文件夹

我发现Get-ChildItem "C:\path\to\folder to zip" -Recurse -Exclude *.txt, *.pdf | %{7za.exe a -mx3 "C:\path\to\newZip.zip" $_.FullName} 作为 powershell 命令可以正常工作,但是如何在脚本文件的函数中使用它

请建议...

【问题讨论】:

标签: powershell 7zip


【解决方案1】:

如果该单行代码有效,那么将其放入函数中非常简单:

function Create-Zip([string]$directory, [string]$zipFile, [string[]]$exclude=@())
{
    $pathToZipExe = "C:\Program Files\7-zip\7z.exe"
    Get-ChildItem $directory -Recurse -Exclude $exclude | 
        Foreach {& $pathToZipExe a -mx3 $zipFile $_.FullName}
}

如果您需要排除目录,请将 Get-ChildItem 行更改为:

    Get-ChildItem $directory -Recurse -Exclude $exclude | Where {!$_.PSIsContainer} |

【讨论】:

  • 快速 - 你将这些函数实际放置在哪里,以便 powershell 可以访问它们
  • 您可以将上面的函数放在您的 profile.ps1 脚本中(位于 $home\Documents\WIndowsPowerShell 下)。 PowerShell 将在加载时处理该脚本,并且该函数将可用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
  • 2020-11-03
相关资源
最近更新 更多