【问题标题】:PowerShell Copy Files in Source Folder to Matching Destination Fails With Destination ValuePowerShell 将源文件夹中的文件复制到匹配目标失败并显示目标值
【发布时间】:2021-09-23 02:41:33
【问题描述】:

我正在尝试将一个文件夹中的文件复制到另一个文件夹。文件应位于其父文件夹下的相同文件夹结构中。例如, C:\Users\Boss\One\Two\Alpha\File1.txt 应该去 C:\Users\Boss\One\Two\Beta\File1.txt

在我在 Copy-Item 中指定 Destination 值的最后一行失败:

$sourcedir = "C:\Users\Boss\One\Two\Alpha"
$localdir = "C:\Users\Boss\One\Two\Beta"

# Assumes folders are established by other processes
$sourceContents = Get-ChildItem $sourcedir -Recurse | Where-Object { -not $_.PsIsContainer }
$localContents = Get-ChildItem $localdir | Where-Object { -not $_.PsIsContainer }

Compare-Object $sourceContents $localContents -Property Name,Length,LastWriteTime -PassThru | 
    Where-Object {$_.SideIndicator -eq "<="} | 
    ForEach-Object { 
        Write-Output $_.FullName, $_.Name;
        Write-Output $localdir;
        $a = Join-Path $localdir $_.FullName.SubString($sourcedir.Length);
        Write-Output $a;
        Write-Output $_;
        # Write-Outputs are just to see what's going on
        # Works as expected up until here
        Copy-Item $_ -Destination "$a"
    }

在这种情况下,我收到一条错误消息:“找不到路径 'C:\Users\Boss\File1.txt,因为它不存在。”

我尝试了很多方法,最后尝试了不同的方法来提供目标值。

完成此操作后,源需要成为网络共享。我很早就想使用 Robocopy,但我需要再次将其迁移到使用源 URL。

任何想法将不胜感激。我使用 C# .NET 进行编程,但我一直觉得 PowerShell 是一个需要学习的挑战。


使用 Theo 的示例,我将代码简化为以下内容。请注意,我将文件夹移到了用户之外的一个文件夹中,而不是任何同步文件夹中。

$sourcedir = "C:\Unsynchronised\Alpha"
$localdir = "C:\Unsynchronised\Beta"
# I kept the "local" because I would like to use this for server-client some day

Get-ChildItem -Path $sourcedir -Recurse -File | ForEach-Object {
    $localDirPath = Join-Path -Path $localdir -ChildPath $_.DirectoryName.Substring($sourcedir.Length)
    $localDirFile = Join-Path -Path $localDirPath -ChildPath $_.Name

    Write-Output $_.DirectoryName
    Write-Output $localDirPath
    Write-Output $localDirFile
    $_ | Copy-Item -Destination %localDirPath
}

输出给出...

C:\Unsynchronised\Alpha
C:\Unsynchronised\Beta\
C:\Unsynchronised\Beta\TestFile.txt
C:\Unsynchronised\Alpha\Folder1
C:\Unsynchronised\Beta\Folder1
C:\Unsynchronised\Beta\Folder1\Subfile_1_1.txt

尽管在 Alpha 中有较新的同名文件,但 Beta 中的文件保持不变。

【问题讨论】:

  • 那个错误是关于源文件,而不是目标文件。那是真正的错误消息还是你清理了它,因为我没有看到你是如何从C:\Users\Boss\One\Two\Alpha的源目录获取文件名C:\Users\Boss\File1.txt
  • @Daniel:是和否。是的,我将真正的文件夹“工作”更改为“老板”,这样人们就会知道它是个人用户下的文件夹。我只是碰巧将帐户命名为“工作”。不,这就是结果。我在 C:\Users\Work 的 PowerShell 中工作,所以我认为它正在尝试放置文件。它忽略了 $a 中的值并将文件放在工作目录中,或者尝试这样做。 (编辑:我现在正在调整代码以查看它是否有效,但我不能依赖从我需要文件的根目录运行的脚本。)
  • 好的。我想说的是,当它找不到正在复制的文件时会给出该错误消息。找不到目的地时给出的消息是The filename, directory name, or volume label syntax is incorrect. : 'C:\temp\lkdsffsdf\'
  • 另外,如果你给Copy-Item一个目的地,在这种情况下$a它不会尝试将文件复制到工作目录,除非你给它的目的地是空的。您在脚本中注意到您的$a 变量包含预期的目的地,并附注“在此之前按预期工作”,因此目的地将是 $a 中包含的任何内容。顺便说一句,$a 周围没有引号
  • 关于引号,是的,我认为这是我所做的那些线索之一,它们被抛在了后面,或者尝试任何尝试,以防我语法错误。

标签: powershell


【解决方案1】:

我不会在此使用Compare-Object,而是在一个简单循环中使用if() 条件来测试目标路径中是否已存在文件,如果不存在,则从源路径复制它,并在需要的地方创建子文件夹:

$sourcedir   = "C:\Users\Boss\One\Two\Alpha"
$destination = "C:\Users\Boss\One\Two\Beta"

# get a string array of files already in the destination path (FullNames only)
$existingFiles = (Get-ChildItem -Path $destination -Recurse -File).FullName

Get-ChildItem -Path $sourcedir -Recurse -File | ForEach-Object {
    $targetPath = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($sourcedir.Length)
    $targetFile = Join-Path -Path $targetPath -ChildPath $_.Name
    # test if the file is not already present in the destination
    if ($existingFiles -notcontains $targetFile) {
        # create the destination subfolder path if this does not yet exist
        $null = New-Item -Path $targetPath -ItemType Directory -Force
        $_ | Copy-Item -Destination $targetPath
    }
}

由于您的问题并未表明您只想复制目标中尚不存在的文件,以及现有文件的较新版本,请参阅下面的编辑版本:

$sourcedir   = 'C:\Unsynchronised\Alpha'
$destination = 'C:\Unsynchronised\Beta'

Get-ChildItem -Path $sourcedir -Recurse -File | ForEach-Object {
    $targetPath = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($sourcedir.Length)
    $targetFile = Join-Path -Path $targetPath -ChildPath $_.Name
    # test if the file is not already present in the destination
    $existingFile = Get-Item -Path $targetFile -ErrorAction SilentlyContinue
    # if there is no such file or that file is older than the one we have in the source directory
    if (!$existingFile -or $_.LastWriteTime -gt $existingFile.LastWriteTime) {
        # create the destination subfolder path if this does not yet exist
        $null = New-Item -Path $targetPath -ItemType Directory -Force
        $_ | Copy-Item -Destination $targetPath -Force
    }
} 

知道这一点,为什么不使用 robocopy 呢?

类似

robocopy.exe $sourcedir $destination /S /XO /COPYALL /R:0 /W:0

在哪里

/S       Do not copy empty directories
/XO      Excludes older files (do not overwrite existing files that are newer in the destination)
/COPYALL Copy ALL file info
/R:0     Number of retries on failures (default 1 million)
/W:0     Wait time between retries in seconds (default is 30 seconds)

【讨论】:

  • 这没有用,虽然我不相信,起初,你提供的东西有什么问题。这是我接下来要尝试的算法,你的可能比我的更优雅。我将使用此尝试的版本作为(不成功的)答案编辑我的 OP,以便您可以清楚地看到。我修改了您的代码以删除 if()。我想我会把它排除在外,无论如何只复制文件,但它仍然没有。不过,这次没有错误消息。我还将文件夹移动到 C:\ 根目录下的文件夹中。
  • @em_sys 请查看我的编辑版本,如果文件比目标中已有的文件更新,该版本也会复制文件
  • 我昨天尝试了 Robocopy,但它在 PS 上不起作用。我从 cmd 尝试过,它确实有效。我今天开始工作的想法是更改 Set-ExecutionPolicy 的设置。我也试过你的
  • (grrr...这是最长 5 分钟的愚蠢编辑器) 我想我通过在比较对象语句中包含 LastWriteTime 来表明我想要更新的文件。对困惑感到抱歉。所以今天,我开始想改变 Set-ExecutionPolicy 的设置。我也尝试了你的新代码,它奏效了。但话又说回来,我尝试了自己的代码并且它有效。所以后来我想也许它确实是 Set-ExecutionPolicy,所以我重新启动了我的计算机并尝试了另一个试验。它适用于我的代码和昨天的政策。我不确定为什么今天一切正常,但你的代码帮助了西奥。
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多