【问题标题】:Powershell Copy-Item - Exclude only if the file exists in destinationPowershell Copy-Item - 仅当文件存在于目标中时才排除
【发布时间】:2014-11-18 07:21:07
【问题描述】:

以下是我的 powershell 脚本中的确切场景。

$Source = "C:\MyTestWebsite\"
$Destination = "C:\inetpub\wwwroot\DemoSite"
$ExcludeItems = @(".config", ".csproj")

Copy-Item "$Source\*" -Destination "$Destination" -Exclude $ExcludeItems -Recurse -Force

如果目标文件夹中不存在 .config 和 .csproj 文件,我希望此代码复制它们。当前脚本只是将它们排除在外,无论它们是否存在。 目标是,我不希望脚本覆盖 .config 和 .csproj 文件,但如果它们在目标位置不存在,它应该复制它们。

知道脚本中需要进行哪些更正吗?

对此的任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 某种使用 Test-Path 的 If 语句似乎是有序的。
  • 这听起来像是 Robocopy 的工作,而不是 PowerShell 脚本。

标签: powershell powershell-2.0 powershell-remoting copy-item


【解决方案1】:

这应该非常接近您想要做的事情

$Source = "C:\MyTestWebsite\"
$Destination = "C:\inetpub\wwwroot\DemoSite"

$ExcludeItems = @()
if (Test-Path "$Destination\*.config")
{
    $ExcludeItems += "*.config"
}
if (Test-Path "$Destination\*.csproj")
{
    $ExcludeItems += "*.csproj"
}

Copy-Item "$Source\*" -Destination "$Destination" -Exclude $ExcludeItems -Recurse -Force

【讨论】:

    【解决方案2】:
    $Source = "C:\MyTestWebsite"
    $Destination = "C:\inetpub\wwwroot\DemoSite"
    
    $sourceFileList = Get-ChildItem "C:\inetpub\wwwroot\DemoSite" -Recurse
    
    foreach ($item in $sourceFileList)
    {
        $destinationPath = $item.Path.Replace($Source,$Destination)
        #For every *.csproj and *.config files, check whether the file exists in destination
        if ($item.extension -eq ".csproj" -or $item.extension -eq ".config")
        {
            if ((Test-Path $destinationPath) -ne $true)
            {
                Copy-Item $item -Destination $destinationPath -Force
            }
        }
        #If not *.csproj or *.config file then copy it directly
        else
        {
            Copy-Item $item -Destination $destinationPath -Force
        }
    }
    

    【讨论】:

      【解决方案3】:

      SKaDT 的解决方案对我有用。

      Copy-Item -Path (Get-ChildItem -Path E:\source\*.iso).FullName -Destination E:\destination -Exclude (Get-ChildItem -Path E:\destination\*.iso).Name -Verbose
      

      (Get-ChildItem -Path E:\source\*.iso).FullName 将收集具有完整驱动器、路径和文件名的所有源文件。使用-Exclude 参数,(Get-ChildItem -Path E:\destination\*.iso).Name 收集目标文件夹中的所有 *.iso 文件并排除所有这些文件。 结果:将所有 *.iso 文件从源复制到目标,但不包括目标文件夹中存在的所有 *.iso 文件。

      【讨论】:

        【解决方案4】:

        您可以使用该单行命令仅复制目标位置不存在的文件,例如任务计划程序

        Copy-Item -Path (Get-ChildItem -Path E:\source\*.iso).FullName -Destination E:\destination -Exclude (Get-ChildItem -Path E:\destination\*.iso).Name -Verbose
        

        cmdlet 通过掩码 (*.iso) 获取文件夹上的所有文件,然后查找目标文件夹并排除目标文件夹中存在的所有文件名

        【讨论】:

        • 欢迎您!请在您的回答中附上解释。仅代码答案被发送到“低质量帖子”审查队列以进行潜在删除。您可以随时修改和改进您的答案。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-21
        • 2014-06-06
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        • 2019-12-02
        • 2016-07-11
        相关资源
        最近更新 更多