Windows PowerShell에 파일이 있는지 확인 하시겠습니까?


112

디스크의 두 영역에서 파일을 비교하고 이전 수정 날짜가있는 파일 위에 최신 파일을 복사하는이 스크립트가 있습니다.

$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을 사용하여 파일이 있는지 확인하는 방법을 알려줄 수 있습니까?

답변:


197

cmdlet에 대한 대안 을 제공 하기 위해 (아무도 언급하지 않았으므로) :Test-Path

[System.IO.File]::Exists($path)

(거의) 같은 일을

Test-Path $path -PathType Leaf

와일드 카드 문자에 대한 지원 없음을 제외하고



1
예 @orad, 나는 부정이 존재 () 호출과 답변을 게시, 그것을보고 있지만 ;-) 같은 긍정적 인 반응을 만났다되지 않았습니다
마티아스 R. Jessen를

5
사용 [System.IO.File]::Exists도 것은 다른 상대 경로를 해결 하고, Test-Path비 filepaths (예를 들어, 레지스트리 위치)와 함께 사용할 수 있습니다. 사용 Test-Path.
jpmc26

2
@Jamie Native .NET 메서드는 일반적으로 powershell의 현재 파일 시스템 경로가 아닌 프로세스의 작업 디렉터리에 상대적인 경로를 확인합니다. 당신은 할 수 있습니다[System.IO.File]::($(Join-Path $PWD $path))
Mathias R. Jessen

1
그리고 만약 당신이 그것이 [System.IO.Directory]::Exists($path)폴더를위한 것이라고 생각하지 않았다면 . 둘 다 내 시스템에서 UNC 경로를 지원하지만 숨겨진 공유를 수행 $하려면 경로에서 "`$"로 이스케이프하는 것을 기억하십시오.
Chris Rudd

71

사용 테스트 경로 :

if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
  Write-Warning "$userFile absent from both locations"
}

ForEach루프에 위의 코드를 배치 하면 원하는 작업을 수행 할 수 있습니다.


22

사용하려는 Test-Path:

Test-Path <path to file> -PathType Leaf

7

파일이 있는지 확인하는 표준 방법은 Test-Pathcmdlet을 사용하는 것입니다.

Test-Path -path $filename

6

Test-Pathcmd-let을 사용할 수 있습니다 . 그래서 ...

if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
    Write-Host "$file doesn't exist in both locations."
}

0
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
  }
}

-4

Test-Path는 이상한 대답을 줄 수 있습니다. 예를 들어 "Test-Path c : \ temp \ -PathType leaf"는 false를 제공하지만 "Test-Path c : \ temp * -PathType leaf"는 true를 제공합니다. 슬퍼 :(

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.