检查Windows PowerShell中是否存在文件?

Sam*_*tar 56 powershell powershell-3.0

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

$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
       }
}
Run Code Online (Sandbox Code Playgroud)

这是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
Run Code Online (Sandbox Code Playgroud)

我想修改它,以便它避免这样做,如果文件不存在于这两个区域并打印警告消息.有人能告诉我如何使用PowerShell检查文件是否存在?

Mat*_*sen 122

只需提供替代Test-Pathcmdlet的(因为没有人提到它):

[System.IO.File]::Exists($path)
Run Code Online (Sandbox Code Playgroud)

是(差不多)同样的事情

Test-Path $path -PathType Leaf
Run Code Online (Sandbox Code Playgroud)

除了不支持通配符

  • 使用`[System.IO.File] :: Exists`也[以不同的方式解析相对路径](/sf/ask/787224791/),`Test-Path`可以与非文件路径一起使用(例如,注册地点).使用`Test-Path`. (3认同)
  • @Jamie Native .NET 方法通常解析相对于进程工作目录的路径,不一定是 powershell 中的当前 FileSystem 路径。你可以做`[System.IO.File]::($(Join-Path $PWD $path))` (2认同)
  • 如果您没有猜到它是文件夹的“[System.IO.Directory]::Exists($path)”。两者都支持我的系统上的 UNC 路径,但要执行隐藏共享,请记住将路径中的“$”转义为“$” (2认同)

arc*_*444 46

使用测试路径:

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

将上面的代码放在ForEach循环中应该可以做到你想要的


God*_*ter 14

您想使用Test-Path.

Test-Path <path to file> -PathType Leaf
Run Code Online (Sandbox Code Playgroud)


Mik*_*ard 9

查看文件是否存在的标准方法是使用Test-Pathcmdlet。

Test-Path -path $filename
Run Code Online (Sandbox Code Playgroud)


Spe*_*ian 7

您可以使用Test-Pathcmd-let。所以像...

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