Powershell Copy-Item - 仅当文件存在于目标中时排除

时间:2014-11-18 07:21:07

标签: powershell powershell-v2.0 powershell-remoting copy-item

以下是我的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文件,但如果它们不在目的地,它应该复制它们。

想知道脚本中需要哪些更正?

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

由于

4 个答案:

答案 0 :(得分:3)

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

$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

答案 1 :(得分: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
    }
}

答案 2 :(得分:0)

SKaDT 的解决方案对我有用。

=IF(Name ="Jhon","2")
=IF(Name ="Mike","1") 
=IF(Name ="Jane","3")

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 收集目标文件夹中的所有 *.iso 文件并排除所有这些文件。 结果:将所有 *.iso 文件从源复制到目标,但排除目标文件夹中存在的所有 *.iso 文件。

答案 3 :(得分:-1)

您可以使用该oneline命令仅复制目标位置上不存在的文件,例如Task Scheduler

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

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