问题描述
我只是想将一些文件从一个目录复制到另一个目录。问题是文件确实被复制了,但是对于每个文件我都会得到一个错误提示,我无权访问目标目录。错误中显示的目标目录不是目录而是文件名,实际上是文件名实际复制的文件
例如:
"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"
解决方法
我使用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"