Cal*_*Liu 2 powershell path-variables environment-variables
如何使用 PowerShell 判断指定文件夹是否在我的 PATH 中?
像这样的函数会很棒:
function FolderIsInPATH($Path_to_directory) {
# If the directory is in PATH, return true, otherwise false
}
Run Code Online (Sandbox Code Playgroud)
Plu*_*uto 17
离开这个问题,您不需要为此提供函数,但可以通过以下方式检索$Env:Path
:
$Env:Path -split ";" -contains $directory
Run Code Online (Sandbox Code Playgroud)
运算-contains
符不区分大小写,这是一个好处。将其放在函数中以确保修剪尾部斜杠可能很有用,但这并不常见:
function inPath($directory) {
return ($Env:Path -split ';').TrimEnd('\') -contains $directory.TrimEnd('\')
}
Run Code Online (Sandbox Code Playgroud)
有很多答案$path.Split(";")
可以满足$path -split ";"
99.9% 的现实场景,但Joey对此类似问题的接受答案有一条评论:
包含分号的引用路径将会失败。
基本上,这有点边缘情况,但这PATH
在 Windows 上完全有效:
c:\temp;"c:\my ; path";c:\windows
Run Code Online (Sandbox Code Playgroud)
所以这里有一堆乱七八糟的代码来解决这个问题......
function Test-IsInPath
{
param( [string] $Path, [string] $Folder )
# we're going to treat the path as a csv record, but we
# need to know how many columns there are so we can create
# some fake header names. this might give a higher count
# than the real value if there *are* quoted folders with
# semicolons in them, but that's not really an issue
$columnCount = $Path.Length - $Path.Replace(";","").Length
# generate the list of column names. the actual names
# don't matter - it's just so ConvertFrom-Csv treats our
# PATH as a data row instead of a header row
$headers = 0..$columnCount
# parse the PATH as a csv record using ";" as a delimiter
$obj = $path | ConvertFrom-Csv -header $headers -delimiter ";"
# extract an array of all the values (i.e. folders)
# in the record we just parsed
$entries = $obj.psobject.properties.value
# check if the folder we're looking for is in the list
return $entries.Contains($Folder)
}
Run Code Online (Sandbox Code Playgroud)
这是否是比简单split
方法“更好”的答案取决于您是否希望在您的文件夹中包含包含分号的引用文件夹PATH
:-)...
用法示例:
PS C:\> Test-IsInPath -Path $env:PATH -Folder "c:\temp"
False
PS C:\> Test-IsInPath -Path "c:\temp;`"c:\my ; path`";c:\windows" -Folder "c:\temp"
True
PS C:\> Test-IsInPath -Path "c:\temp;`"c:\my ; path`";c:\windows" -Folder "c:\my ; path"
True
Run Code Online (Sandbox Code Playgroud)
笔记
这仍然没有解决的是以尾随“\”结束(或不结束)的路径 - 例如测试何时C:\temp
包含PATH
,C:\temp\
反之亦然。
它也没有解决此处列出的路径处理的任何其他无数异常:如何检查%PATH%中是否存在目录