【问题标题】:Skip file copy if target exist - PowerShell如果目标存在则跳过文件复制 - PowerShell
【发布时间】:2021-10-26 00:41:20
【问题描述】:

你能帮忙吗?我有以下 PowerShell 代码将文件 (test.txt) 复制到每个用户的漫游文件夹中。有用。但是如果test-old.txt(这是以前重命名的文件)已经存在,我想跳过复制文件。提前感谢您的帮助。

fyi - 如果可行的话,我很高兴有一个新代码。

$Source = '\\ser04\h\AppsData\test.txt'

$Destination = 'C:\users\*\AppData\Roaming\SAP\Common\'

Get-ChildItem $Destination | ForEach-Object {Copy-Item -Path $Source -Destination $_ -Force}

【问题讨论】:

    标签: powershell copy skip script


    【解决方案1】:

    假设test-old.txt 的路径是每个用户的..\SAP\Common\ 文件夹,您只需在现有代码中添加if 条件即可检查该文件是否存在于所述文件夹中。一个简单的方法是使用Test-Path。

    如果您想定位Default 和Default User 文件夹,请记得添加-Force 切换到Get-ChildItem。

    $Source = '\\ser04\h\AppsData\test.xml'
    $Destination = 'C:\users\*\AppData\Roaming\SAP\Common\'
    
    Get-ChildItem $Destination | ForEach-Object {
        
        $testOld = Join-Path $_.FullName -ChildPath 'test-old.txt'
    
        if(-not(Test-Path $testOld))
        {
            Copy-Item -Path $Source -Destination $_ -Force
        }
    }
    

    【讨论】:

    • 非常感谢您的回复,我运行了它,但如果文件不存在,它不会复制文件。我在这段代码中遗漏了什么?
    • @RIC 尝试使用更新后的代码
    • 那工作@Santiago,你是救生员。非常感谢你,伙计。你可以帮我个忙吗?请用我的其他名称替换服务器名称。
    • 你是个绅士。谢谢,伙计。
    猜你喜欢
    • 1970-01-01
    • 2012-04-19
    • 2022-11-15
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多