web-dev-qa-db-ja.com

Windows PowerShellにファイルが存在するかどうかを確認しますか?

このスクリプトを使用して、ディスクの2つの領域のファイルを比較し、最新のファイルを変更日が古いものに上書きします。

$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を使用してファイルが存在するかどうかを確認する方法を教えてもらえますか?

49

Test-Pathコマンドレット代替 を提供するだけです(誰も言及していないため):

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

(ほぼ)同じことをする

Test-Path $path -PathType Leaf

ワイルドカード文字のサポートを除く

104

Test-Path を使用します。

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

上記のコードをForEachループに配置すると、必要な処理が行われます

44
arco444

Test-Pathを使用します。

Test-Path <path to file> -PathType Leaf
13
GodEater

ファイルが存在するかどうかを確認する標準的な方法は、Test-Pathコマンドレットを使用することです。

Test-Path -path $filename
3
Mike Shepard

Test-Path cmd-letを使用できます。のようなもの...

if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
    Write-Host "$file doesn't exist in both locations."
}
3
Speerian
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
  }
}
0
M-A Charlotte