PowerShell 5.1仅复制目录结构,指定扩展名文件无法复制
问题:PowerShell 5.1远程复制指定扩展名文件失败,目录结构同步成功但文件未复制
我正在编写PowerShell 5.1脚本,需将本地(源端)服务器指定目录的结构及文件复制到远程(目标端)服务器,要求仅复制.p12、.properties、.pem等指定扩展名的文件,且满足以下任一条件时执行复制:
- 目标端不存在该文件
- 源文件的修改时间晚于目标端文件
目前遇到的问题是:目录结构已成功复制到目标端,但指定扩展名的文件并未被复制过去,已花费近10小时排查原因,相关代码如下:
foreach ($fileS1 in Get-ChildItem $RootFolder -Recurse) { $FolderNameS1 = $fileS1.FullName $FolderNameNewS1 = $fileS1.FullName # check if the path on the remote session exists $ValidPathS1 = Invoke-Command -Session $Session1 -ScriptBlock { Test-Path -Path $using:FolderNameNewS1 } If ($ValidPathS1 -eq $False) { #create the folder structure if ($fileS1.PSIsContainer -eq $True) { Invoke-Command -Session $Session1 -ScriptBlock { New-Item -Path $using:FolderNameNewS1 -ItemType Directory -Verbose } } } # Get the files in the source folder $sourceFiles = Get-ChildItem $FolderNameS1 -Recurse # Get the files in the destination folder $destinationFiles = Invoke-Command -Session $Session1 -ScriptBlock { Get-ChildItem $using:FolderNameNewS1 -Recurse } # Compare the last write time of each source file with the last write time of its corresponding destination file $extensions = "p12", "properties", "pem" foreach ($sourceFile in $sourceFiles) { if($extensions -contains $sourceFile.Extension){ $fileCopied = $False # check if the file on the remote session exists $destinationFilePath = Invoke-Command -Session $Session1 -ScriptBlock { $destFilePath = Join-Path $using:FolderNameNewS1 $using:sourceFile.Name if(!(Test-Path $destFilePath)){ New-Item -Path $destFilePath -ItemType File -Force } return $destFilePath } if($destinationFilePath -ne ""){ $destinationFile = Invoke-Command -Session $Session1 -ScriptBlock { Get-Item $using:destinationFilePath } $remoteFileExist = Invoke-Command -Session $Session1 -ScriptBlock { Test-Path $using:destinationFilePath } if(!$remoteFileExist){ Copy-Item $sourceFile.FullName -Destination $FolderNameNewS1 -ToSession $Session1 -Force -Verbose } else{ $remoteLastWriteTime = Invoke-Command -Session $Session1 -ScriptBlock { (Get-Item $using:destinationFilePath).LastWriteTime } $remoteLastWriteTime = $remoteLastWriteTime.ToLocalTime() # Compare the last write time of source file and destination file if ($sourceFile.LastWriteTime -gt $remoteLastWriteTime) { #copy only the files with the specified extensions if($extensions -contains $sourceFile.Extension){ Copy-Item $sourceFile.FullName -Destination $FolderNameNewS1 -ToSession $Session1 -Force -Verbose $fileCopied = $True } } } if ($fileCopied -eq $True) { #remove the source file # Remove-Item $sourceFile.FullName -Force -Verbose -ErrorAction SilentlyContinue $fileCopied = $False } } } }
注:使用PSSession远程连接目标服务器,$RootFolder为源端的根目录。
内容的提问来源于stack exchange,提问作者Freshzak187
相关产品推荐
相关产品推荐

