【问题标题】:Error While Copying files using Powershell使用 Powershell 复制文件时出错
【发布时间】:2020-08-13 07:51:16
【问题描述】:

我只是想将一些文件从一个目录复制到另一个目录。问题是,文件确实被复制了,但是对于每个文件,我都会收到一条错误消息,说我无权访问目标目录。错误中显示的目标目录不是目录,而是文件名,实际上是实际被复制的文件

例如:

"C:\Users\Administrator\Desktop\temp\FileExport\Sample\archive\Arc9wa\samplesys\data\UPR00000\0000003E.bmp"

如何防止这种情况发生?我做错了什么?

我的复制文件命令:

Copy-Item "$File" -Destination "$Destination" -Recurse -force

完整代码如下:

[string]$samplepath = Resolve-Path /*\config\serversetup2
    $first_letter= $samplepath.SubString(0,1)
    $dpath=$first_letter+":"
    $path = Get-Location
    Copy-Item '/*\config\serversetup2' -Destination $dpath'\temp\serversetup2\' -recurse -force
   
 $samplepath -match'(?<content>.*)config'
        $respath= $matches['content']
        $fileexport= "\FileExport"
        [String[]]$Destination = Join-Path -Path $path -ChildPath $fileexport
        [String[]]$Source = $respath
        [String[]]$FilePattern = "*"

    $Result = @()
        Write-Host "Copying '$($Source -join ", ")' to '$($Destination -join ", ")'..." -ForegroundColor Green
        $FileCount = (Get-ChildItem $Source -Recurse -File -Include $FilePattern -ErrorAction SilentlyContinue).Count
        $i = 0
        $NotFound = $true
        $Duration = Measure-Command {
            foreach ($File in (Get-ChildItem -Path $Source -Recurse -File -Include $FilePattern -ErrorAction SilentlyContinue)) {
                global:$i++
                Write-Progress -Activity "Copying '$($Source -join ", ")' to '$($Destination.FullName)'" -Status "Copied $i out of $FileCount..." -PercentComplete ($i/$FileCount*100)
                Write-Verbose "Copying '$($Source -join ", ")' to '$($Destination.FullName)'"
                foreach ($File in $Source) {
                Copy-Item "$File" -Destination "$Destination" -Recurse -force
                }
            }
        }
    Write-Host "Finished Export"

【问题讨论】:

  • 一方面:您将$Destination 定义为字符串数组,但稍后将其视为DirectoryInfo 对象。字符串数组没有FullName 属性

标签: powershell copy-item


【解决方案1】:

我使用的是 Robocopy,而不是使用 Copy-Item。我的代码中也有很多错误。这是我的新代码工作正常:

[string]$samplepath = Resolve-Path /*\temp
$samplepath -match'(?<content>.*)temp'
$respath= $matches['content']

$first_letter= $samplepath.SubString(0,1)
$dpath=$first_letter+":"
$path = Get-Location
$exppath = Join-Path -Path "$path\" -ChildPath "\FileExport"
New-Item -Path "$dpath\Sample" -ItemType Directory -force
$newpath = Join-Path -Path "$dpath" -ChildPath "Sample"
Write-Host "Starting import"

 robocopy "$exppath" "$newpath" /e


Write-Host "Process finished"

【讨论】:

    猜你喜欢
    • 2015-07-16
    • 2021-11-27
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2017-08-03
    • 1970-01-01
    相关资源
    最近更新 更多