在PowerShell

时间:2017-06-01 18:52:00

标签: powershell zip

希望其他脚本编写者可以帮助解决这个问题:)现在我已经解决了这个问题几个小时了。

我尝试使用PowerShell压缩某些文件夹。 我的文件夹结构是

备份
BoxIntranet
组件
内容
数据库
Exec的
文件
日志
多浏览
多浏览器\传统\定制

ParentPortal
ParentPortal \定制
StudentPortal
StudentPortal \定制
更新
WebDav

上面的每一个都有很多文件和文件夹,但这些是我主要感兴趣的文件和文件夹。 我试图在PowerShell中使用Write-Zip或Compress-Archive方法将其全部压缩,但我的条件是。

  1. 只能从根

  2. 压缩内容,文件,数据库文件夹
  3. 还应备份Multibrowser \ Legacy \ customization,StudentPortal \ Customization和ParentPortal \ customization文件夹。

  4. zip文件中的文件夹结构应保持不变,这意味着zip文件的Root应包含Content,Files,Database,Multibrowser,ParentPortal和StudentPortal文件夹。虽然内容,文件和数据库文件夹应该压缩所有内容,但Multibrowser,ParentPortal和StudentPortal文件夹应该只包含指定的子目录及其中的所有文件。

  5. 代码:

    $FilesAndInclude = @("Content", "Files", "Database", "Multibrowser\Legacy\customisation", 
                         "StudentPortal\customisation", "ParentPortal\customisation", 
                         "BoxIntranet\customisation")
    $FilesToExclude = @("connectionstrings.config", "inc_dbconn.asp")
    Get-ChildItem -Path "C:\Folder" -Include $FilesAndInclude -Recurse -Exclude $FilesToExclude|
        Compress-Archive -DestinationPath "Archive.zip"
    

    我已经尝试了上述内容并且它没有做任何事情但是如果我删除-Include参数然后它会拉上所有内容但是不保留文件夹结构。

    有没有办法在powershell中完成我的目标?

1 个答案:

答案 0 :(得分:1)

好的,首先,您使用-Include参数时遇到困难的原因是因为它仅用于包含您指定的内容。因此,它将查看事物的名称(而不是它们的路径),并检查列表,如果它匹配列表中的内容,它将包括该项目。由于您只列出文件夹名称,因此仅包含这些文件夹(但不包含其内容)。所以你不能通过这种方式传递任何文件。为了解决这个问题,您需要首先构建文件列表,然后将其传递给cmdlet以进行压缩。

下一期是Compress-Archive没有存储路径信息,因此您需要使用Write-Zip。我已经包含了我认为你想要的cmdlet。

$FilesAndInclude = @("Content", "Files", "Database", "Multibrowser\Legacy\customisation", 
                     "StudentPortal\customisation", "ParentPortal\customisation", 
                     "BoxIntranet\customisation")
$FilesToExclude = @("connectionstrings.config", "inc_dbconn.asp")
[array]$FilesToZip = Get-ChildItem .\* -Exclude $FilesToExclude -File
$FilesToZip += $FilesAndInclude | ForEach{Get-ChildItem .\$_ -Exclude $FilesToExclude -File}
$FilesToZip | Write-Zip -EntryPathRoot $(Resolve-Path .\|Select -Expand Path) -OutputPath Archive.zip