Expand %varname%

Line Break

Author: Frank-Peter (77 Articles)

Hello again! Today I will share a small PowerShell function, ExpandEnvironmentVariables that I use to expand environment variables that are written in legacy syntax (%varname%). For instance, the function is useful if you read values from configuration text files that may contain variable names.

ExpandEnvironmentVariables supports PowerShell 1 and 2. It is designed to accept pipeline input and uses the ExpandEnvironmentVariables() method of the System.Environment class to resolve variables. The function supports nested variable references

function ExpandEnvironmentVariables {
	param (
		[string]$String
	)
	begin {
		function _exp ([string]$str) {
			$s1 = $str
			$s2 = [System.Environment]::ExpandEnvironmentVariables($s1)
			while ($s2 -ne $s1) {
				$s1 = $s2
				$s2 = [System.Environment]::ExpandEnvironmentVariables($s1)
			}
			$s2
		}
	}
	process {
		if ($_) {
			$String = $_
		} elseif (!$String) {
			throw 'No value for the String parameter specified.'
		}
		_exp -str $String
	}
}
Bookmark and Share
Tags »

Author:Frank-Peter
Date: Wednesday, 19. May 2010 12:08
Trackback: Trackback-URL Category: Scripting, Windows PowerShell

Feed for the post RSS 2.0 Comment this post

Submit comment

CAPTCHA Image CAPTCHA Audio
Refresh Image