在 Windows PowerShell 中检查文件是否存在? [英] Check if a file exists or not in Windows PowerShell?

查看:142
本文介绍了在 Windows PowerShell 中检查文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本,它比较磁盘两个区域中的文件,并将最新的文件复制到具有较旧修改日期的文件上.

I have this script which compares files in two areas of the disk and copies the latest file over the one with the older modified date.

$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的格式

Here is the format of 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 检查文件是否存在吗?

I would like to modify this so that it avoids doing this if the file does not exist in both areas and prints a warning message. Can someone tell me how I can check if a file exists using PowerShell?

推荐答案

只为提供 替代 Test-Path cmdlet(因为没有人提到它):

Just to offer the alternative to the Test-Path cmdlet (since nobody mentioned it):

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

做(几乎)与

Test-Path $path -PathType Leaf

除了不支持通配符

这篇关于在 Windows PowerShell 中检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆