디스크의 두 영역에서 파일을 비교하고 이전 수정 날짜가있는 파일 위에 최신 파일을 복사하는이 스크립트가 있습니다.
$filestowatch=get-content C:\H\files-to-watch.txt
$adminFiles=dir C:\H\admin\admin -recurse | ? { $fn=$_.FullName; ($filestowatch | % {$fn.contains($_)}) -contains $True}
$userFiles=dir C:\H\user\user -recurse | ? { $fn=$_.FullName; ($filestowatch | % {$fn.contains($_)}) -contains $True}
foreach($userfile in $userFiles)
{
      $exactadminfile= $adminfiles | ? {$_.Name -eq $userfile.Name} |Select -First 1
      $filetext1=[System.IO.File]::ReadAllText($exactadminfile.FullName)
      $filetext2=[System.IO.File]::ReadAllText($userfile.FullName)
      $equal = $filetext1 -ceq $filetext2 # case sensitive comparison
      if ($equal) {
        Write-Host "Checking == : " $userfile.FullName
        continue;
      }
      if($exactadminfile.LastWriteTime -gt $userfile.LastWriteTime)
      {
         Write-Host "Checking != : " $userfile.FullName " >> user"
         Copy-Item -Path $exactadminfile.FullName -Destination $userfile.FullName -Force
       }
       else
       {
          Write-Host "Checking != : " $userfile.FullName " >> admin"
          Copy-Item -Path $userfile.FullName -Destination $exactadminfile.FullName -Force
       }
}
다음은 files-to-watch.txt 형식입니다.
content\less\_light.less
content\less\_mixins.less
content\less\_variables.less
content\font-awesome\variables.less
content\font-awesome\mixins.less
content\font-awesome\path.less
content\font-awesome\core.less
파일이 두 영역에 모두 존재하지 않고 경고 메시지를 인쇄하는 경우이를 방지하도록 수정하고 싶습니다. 누군가 PowerShell을 사용하여 파일이 있는지 확인하는 방법을 알려줄 수 있습니까?
답변
답변
사용 테스트 경로 :
if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
  Write-Warning "$userFile absent from both locations"
}
ForEach루프에 위의 코드를 배치 하면 원하는 작업을 수행 할 수 있습니다.
답변
사용하려는 Test-Path:
Test-Path <path to file> -PathType Leaf
답변
파일이 있는지 확인하는 표준 방법은 Test-Pathcmdlet을 사용하는 것입니다.
Test-Path -path $filename
답변
Test-Pathcmd-let을 사용할 수 있습니다 . 그래서 …
if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
    Write-Host "$file doesn't exist in both locations."
}
답변
cls
$exactadminfile = "C:\temp\files\admin" #First folder to check the file
$userfile = "C:\temp\files\user" #Second folder to check the file
$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations
foreach ($filename in $filenames) {
  if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
    Write-Warning "$filename absent from both locations"
  } else {
    Write-Host " $filename  File is there in one or both Locations" #if file exists there at both locations or at least in one location
  }
}
답변
Test-Path는 이상한 대답을 줄 수 있습니다. 예를 들어 “Test-Path c : \ temp \ -PathType leaf”는 false를 제공하지만 “Test-Path c : \ temp * -PathType leaf”는 true를 제공합니다. 슬퍼 🙁
