2017-10-04 154 views
0

我已經搜索了這個並找到了很多答案。但是,他們似乎都沒有工作。使用powershell檢查遠程系統中是否存在文件/文件夾

我正在使用一個腳本,將用於從本地機器複製一些文件到遠程服務器。在複製文件之前,我需要檢查文件/文件夾是否已經存在。如果該文件夾不存在,則創建一個新文件夾,然後複製這些文件。如果該文件已經存在於指定位置,則只需覆蓋該文件。

我得到了如何做到這一點的邏輯。但是,出於某種原因,Test-Path似乎不起作用。

$server = #list of servers 
$username = #username 
$password = #password 
$files = #list of files path to be copied 
foreach($server in $servers) { 
    $pw = ConvertTo-SecureString $password -AsPlainText -Force 
    $cred = New-Object Management.Automation.PSCredential ($username, $pw) 
    $s = New-PSSession -computerName $server -credential $cred 
    foreach($item in $files){ 
     $regex = $item | Select-String -Pattern '(^.*)\\(.*)$' 
     $destinationPath = $regex.matches.groups[1] 
     $filename = $regex.matches.groups[2]   
     #check if the file exists on local system 
     if(Test-Path $item){ 
      #check if the path/file already exists on remote machine 
      #First convert the path to UNC format before checking it 
      $regex = $item | Select-String -Pattern '(^.*)\\(.*)$' 
      $filename = $regex.matches.groups[2] 
      $fullPath = $regex.matches.groups[1] 
      $fullPath = $fullPath -replace '(.):', '$1$' 
      $unc = '\\' + $server + '\' + $fullPath 
      Write-Host $unc 
      Test-Path $unC#This always returns false even if file/path exists 
      if(#path exists){ 
       Write-Host "Copying $filename to server $server" 
       Copy-Item -ToSession $s -Path $item -Destination $destinationPath 
      } 
      else{ 
       #create the directory and then copy the files 
      } 
     } 
     else{ 
      Write-Host "$filename does not exists at the local machine. Skipping this file" 
     }   
    } 
    Remove-PSSession -Session $s 
} 

檢查遠程計算機上文件/路徑是否存在的條件總是失敗。不知道爲什麼。

我在powershell上手動嘗試了以下命令,該命令在遠程計算機上返回true,在本地計算機上返回false。

在本地機器上:

Test-Path '\\10.207.xxx.XXX\C$\TEST' 
False 

在遠程機器:

Test-Path '\\10.207.xxx.xxx\C$\TEST' 
True 
Test-Path '\\localhost\C$\TEST' 
True 

所以,很顯然,此命令就會失敗,即使我嘗試手動或通過腳本。但是當我嘗試從遠程系統或服務器上執行命令時,命令就會通過。

但我需要檢查該文件是否存在於本地系統的遠程機器上。

我錯過了什麼嗎?有人能幫我理解這裏發生了什麼嗎?

謝謝!

+0

爲什麼不使用Robocopy處理副本? – Snak3d0c

+0

我認爲我們看到了這個問題,你能告訴我們'$ Files'有幾行嗎? – FoxDeploy

回答

1

首先,你沒有使用任何PSSession。他們看起來多餘。

如果您的本地路徑與目的地相同,並且您使用的是WMF/Powershell 4或更新版本;我建議您停止使用正則表達式和UNC路徑,並執行以下操作,這會簡化並刪除大部分代碼:

$existsOnRemote = Invoke-Command -Session $s {param($fullpath) Test-Path $fullPath } -argumentList $item.Fullname; 
if(-not $existsOnRemote){ 
    Copy-Item -Path $item.FullName -ToSession $s -Destination $item.Fullname; 
} 
+0

謝謝老兄。有效! – jayaganthan

+0

完成:) @CmdrTchort – jayaganthan

相關問題