2017-10-04 13 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