Equivalent of *Nix 'which' command in PowerShell?

后端 未结 14 2200
刺人心
刺人心 2020-11-28 00:16

How do I ask PowerShell where something is?

For instance, \"which notepad\" and it returns the directory where the notepad.exe is run from according to the current

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 01:00

    Use:

    function Which([string] $cmd) {
      $path = (($Env:Path).Split(";") | Select -uniq | Where { $_.Length } | Where { Test-Path $_ } | Get-ChildItem -filter $cmd).FullName
      if ($path) { $path.ToString() }
    }
    
    # Check if Chocolatey is installed
    if (Which('cinst.bat')) {
      Write-Host "yes"
    } else {
      Write-Host "no"
    }
    

    Or this version, calling the original where command.

    This version also works better, because it is not limited to bat files:

    function which([string] $cmd) {
      $where = iex $(Join-Path $env:SystemRoot "System32\where.exe $cmd 2>&1")
      $first = $($where -split '[\r\n]')
      if ($first.getType().BaseType.Name -eq 'Array') {
        $first = $first[0]
      }
      if (Test-Path $first) {
        $first
      }
    }
    
    # Check if Curl is installed
    if (which('curl')) {
      echo 'yes'
    } else {
      echo 'no'
    }
    

提交回复
热议问题