【问题标题】:Powershell - Test-path looking for 3 filesPowershell - 寻找 3 个文件的测试路径
【发布时间】:2014-09-04 23:52:45
【问题描述】:

我正在尝试创建一个 powershell 脚本,该脚本将检查文件夹中的 3 个特定文件。如果 3 个文件存在则继续。

我一直在尝试使用 test-path 命令。我得到的最接近的是:

$checkwim = test-path $imagepath\* -include OS.wim, data.wim, backup.wim.

但这对我不起作用,因为如果找到 3 个中的任何一个,它就会返回“True”。我需要确保所有 3 个都存在。

我使用下面的方法让它工作,但我希望有一个更简单\更短的方法。

$checkwimos = test-path $imagepath\* -include OS.wim
$checkwimdata = test-path $imagepath\* -include Data.wim
$checkwimonline = test-path $imagepath\* -include Online.wim

if (($checkwimos -ne $True) -or ($checkwimdata -ne $True) -or ($checkwimonline -ne $True))
{
Echo "WIM file(s) not located.  Script Aborting"
exit
}

有没有更简单的方法来做到这一点?

【问题讨论】:

    标签: powershell if-statement


    【解决方案1】:

    如果您想避免硬编码检查要包含的每种文件类型,您可以执行以下操作:

    $files = @('os.wim','data.wim','backup.wim')
    $checkWim = $files | foreach-object {test-path $imagepath\* -Include $_} | Where-Object {$_ -eq $false}
    If($checkWim -eq $false){"WIM file(s) not located.  Script Aborting"}
    else{
    #do stuff
    }
    

    您也可以导入文件列表而不是创建数组。

    【讨论】:

      【解决方案2】:

      另一种策略:

      $files = @('os.wim','data.wim','backup.wim')
      
      if (($files | foreach {test-path $imagepath\$_}) -contains $false)
       { 
         Echo "WIM file(s) not located.  Script Aborting"
         exit
       }
      

      【讨论】:

      • 谢谢,我最喜欢这个,因为它可以让我们轻松调整文件数量。
      【解决方案3】:

      您的方式已经很简单了,尽管您可以通过以下方式使其更具可读性:

      $checkwimos = test-path (Join-Path $imagepath OS.wim)
      $checkwimdata = test-path (Join-Path $imagepath Data.wim)
      $checkwimonline = test-path (Join-Path $imagepath Online.wim)
      
      if (-not ($checkwimos -and $checkwimdata -and $checkwimonline))
      {
      Echo "WIM file(s) not located.  Script Aborting"
      exit
      }
      

      【讨论】:

        【解决方案4】:

        如果您坚持使用单线,则以下内容应该可行。

        if (@(Get-ChildItem -LiteralPath "C:\temp\" | Where-Object -FilterScript {@("os.wim", "data.wim", "backup.wim") -ccontains $_.Name}).Count -eq 3)
        {
        write "Files were present"
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-03
          • 2012-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-09
          相关资源
          最近更新 更多