#requires -version 2.0 <# ----------------------------------------------------------------------------- Script: Resolve-EnvVariable.ps1 Version: 0.9 Author: Jeffery Hicks http://jdhitsolutions.com/blog http://twitter.com/JeffHicks http://www.ScriptingGeek.com Date: 6/29/2012 Keywords: Comments: "Those who forget to script are doomed to repeat their work." **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** ----------------------------------------------------------------------------- #> Function Resolve-EnvVariable { <# .Synopsis Resolve Windows environmental variables .Description This command accepts strings that contain Windows environmental variables like %WINDIR% and resolves them with their actual value. For example, it will take a string like: %SystemRoot%\system32\WindowsPowerShell\v1.0\ and return: C:\Windows\system32\WindowsPowerShell\v1.0\ If the string doesn't contain something that looks like an environmental variable the original string will be written back to the pipeline. .Parameter String The string to examine. It must contain an environmental variable like %WINDIR%. .Example PS C:\> Resolve-EnvVariable %SystemRoot%\system32\WindowsPowerShell\v1.0\ C:\Windows\system32\WindowsPowerShell\v1.0\ .Example PS C:\> $env:path.split(";") | resolve-envvariable | foreach { if (test-path $_ ) { $fg='Green' } else { $fg='Red' } Write-Host $_ -ForegroundColor $fg } #> [cmdletbinding()] Param( [Parameter(Position=0,ValueFromPipeline=$True,Mandatory=$True, HelpMessage="Enter a string that contains an environmental variable like %WINDIR%")] [ValidateNotNullOrEmpty()] [string]$String ) Begin { Write-Verbose "Starting $($myinvocation.mycommand)" } #Begin Process { #if string contains a % then process it if ($string -match "%\S+%") { Write-Verbose "Resolving environmental variables in $String" #split string into an array of values $values=$string.split("%") | Where {$_} foreach ($text in $values) { #find the corresponding value in ENV: Write-Verbose "Looking for $text" [string]$replace=(Get-Item env:$text -erroraction "SilentlyContinue").Value if ($replace) { #if found append it to the new string Write-Verbose "Found $replace" $newstring+=$replace } else { #otherwise append the original text $newstring+=$text } } #foreach value Write-Verbose "Writing revised string to the pipeline" #write the string back to the pipeline Write-Output $NewString } #if else { #skip the string and write it back to the pipeline Write-Output $String } } #Process End { Write-Verbose "Ending $($myinvocation.mycommand)" } #End } #end Resolve-EnvVariable