2

I am trying to check whether the system has a particular environment variable value that contains a particular string; e.g.:

C:\Program Files\Java\jre1.8.0_271\bin

I found how to check whether an environment variable exists or not:

if ([Environment]::GetEnvironmentVariable('path', 'Machine'))
{
  "Exist in the system!"
}

This works, but I need to know how to check whether the value contains a particular substring or not.

1

1 Answer 1

5

You can try :

$pathContent = [Environment]::GetEnvironmentVariable('path', 'Machine')
$myPath = "C:\WINDOWS\system32"
if ($pathContent -ne $null)
{
  # "Exist in the system!"
  if ($pathContent -split ';'  -contains  $myPath)
  {
    # My path Exists
    Write-Host "$myPath exists"
  }
  else
  {
    Write-Host "$myPath does not exist"
  }
}

The -split operator generate an array of strings in which the -contains operator test if $myPath is inside.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.