Подтвердить что ты не робот

Проверьте, существует ли файл в Windows PowerShell или нет.

У меня есть этот script, который сравнивает файлы в двух областях диска и копирует последний файл по сравнению со старым измененным датом.

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

Вот формат файлов-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?

4b9b3361

Ответ 1

Просто предложите альтернативу в командлете Test-Path (поскольку никто не упоминал об этом):

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

Делает (почти) то же самое, что и

Test-Path $path -PathType Leaf

кроме поддержки подстановочных знаков

Ответ 2

Используйте Test-Path:

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

Размещение приведенного выше кода в цикле ForEach должно делать то, что вы хотите

Ответ 3

Вы хотите использовать тестовый путь.

Test-Path <path to file> -PathType Leaf

Ответ 4

Стандартный способ увидеть, существует ли файл с командлетом Test-Path.

Test-Path -path $filename

Ответ 5

Вы можете использовать Test-Path cmd-let. Так что-то вроде...

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

Ответ 6

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

Ответ 7

Test-Path может дать нечетный ответ. Например. "Test-Path c:\temp\-PathType leaf" дает false, но "Test-Path c:\temp * -PathType leaf" дает значение true. Печально: (