Home > Software engineering >  How can I tell if a specified folder is in my PATH using PowerShell?
How can I tell if a specified folder is in my PATH using PowerShell?

Time:08-05

How can I tell if a specified folder is in my PATH using PowerShell?

A function like this would be great:

function FolderIsInPATH($Path_to_directory) {
    # If the directory is in PATH, return true, otherwise false
}

CodePudding user response:

I would go for something like this

   function FolderIsInPATH {

     param (
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]$your_searched_folder
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]$Path
    )

$Folders = Get-Childitem -Path $Path -Directory

foreach ($Folder in $Folders) {
 if ($Folder.Name -eq $your_searched_folder) {
   ##Folder found
   
  } else {
    ##folder not found
  }

}

}

CodePudding user response:

Going off this question, you don't need a function for this but can retrieve this with $Env:Path:

$Env:Path -split ";" -contains $directory

The -contains operator is case-insensitive which is a bonus. If you really wanted to put it in a function, it would look like this:

function inPath($directory) {
    return $Env:Path -split ";" -contains $directory
}

CodePudding user response:

You can get your PATH using [Environment]::GetEnvironmentVariables()

[Environment]::GetEnvironmentVariables()

Or if you want to get the user environment variables:

[Environment]::GetEnvironmentVariables("User")

Next get the PATH variable:

$Path = [Environment]::GetEnvironmentVariables().Path # returns the PATH

Then check if the specified folder is in your PATH:

$Path.Contains($Path_to_directory   ";")

The function put together:

function FolderIsInPath($Path_to_directory) {
    return [Environment]::GetEnvironmentVariables("User").Path.Contains($Path_to_directory   ";")
}

However, this function is case-sensitive. You can use String.ToLower() to make it not case-sensitive.

function FolderIsInPath($Path_to_directory) {
    return [Environment]::GetEnvironmentVariables("User").Path.ToLower().Contains($Path_to_directory.ToLower()   ";")
}

Now call your function like this:

FolderIsInPath("C:\\path\\to\\directory")

Note that the path must be absolute.

  • Related