脚本中给出的 Compress-Archive 包括脚本本身

Compress-Archive given in a script includes the script itself

如何让 Compress-Archive 只压缩子文件夹结构?现在,脚本本身包含在 .zip 中。或者是否可以将其过滤掉?

我得到的代码如下:

if (!($PSScriptRoot)) { Split-Path $MyInvocation.MyCommand.Path -Parent }
$destination  = Split-Path $MyInvocation.MyCommand.Path -Parent
$source = (Get-ChildItem $PSScriptRoot)
$date = Get-Date -UFormat "%Y-%m-%d"
$zipfile = $destination + "\createdOn" + $date + ".zip"

#Check if file exists
if ([System.IO.File]::Exists($zipfile))
{
    Clear-Host
    Write-Host "File created: " $zipfile
    Compress-Archive -DestinationPath $zipfile -Force -Path $source -CompressionLevel Optimal
}
else
{
    Clear-Host
    Write-Host "File created: " $zipfile
    Compress-Archive -DestinationPath $zipfile -Force -Path $source -CompressionLevel Optimal
}

尝试:

$source = (Get-ChildItem $PSScriptRoot -exclude $MyInvocation.MyCommand)

如果您将 $source 设置为 $PSScriptRoot 的子项目(脚本的父文件夹),然后从这些项目创建一个存档,为什么生成的存档 包含作为该文件夹的子项目之一的脚本?

$source 中删除脚本文件以避免其包含在存档中:

$source = Get-ChildItem $PSScriptRoot |
          Where-Object { $_.FullName -ne $PSCommandPath }