Expanding string in Powershell

Line Break

Author: Martin Zugec (31 Articles)

When you design frameworks, you try to store as much information as possible in external (configuration) files and you try to avoid hardcoding them to scripts themselves.

Problem is that retrieved values are strings and are not expanded.

Therefore if you specify $($Env:WinDir) in your configuration file, output is the same and NOT C:\Windows.

There is easy way how to solve it – use Invoke-Expression:

The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command.

Some of you maybe already noticed where I see a problem – it runs strings as command. Therefore my example would work as expected and C:\Windows is returned, however Format is also valid command ;)

For expanding regular variables, I knew that you could use [System.Environment]::ExpandEnvironmentVariables function. For example

[System.Environment]::ExpandEnvironmentVariables(“%WinDir%\System32”)

will result in “C:\Windows\System32”. However it doesn’t work with Powershell variables and powershell doesn’t support %var% (the syntax most people are used to).

Shay Levy pointed me to function $ExecutionContext.InvokeCommand.ExpandString – this method is used to expand powershell strings:

$ExecutionContext.InvokeCommand.ExpandString($Home)

Beaty of it is that it doesn’t execute commands, so format is not used ;)

To summarize, below is function I finally decided to use in S4Matic for expanding configuration entries:

[System.Environment]::ExpandEnvironmentVariables($ExecutionContext.InvokeCommand.ExpandString($foo))

That way, you can use either $var or $Env:var or %var% in configuration. Simple, yet functional :)

Martin

UPDATE: Fixed typo in ExpandString function name, thanks to Larry Weiss

Bookmark and Share
Tags »

Author:Martin Zugec
Date: Thursday, 26. November 2009 9:50
Trackback: Trackback-URL Category: S4Matic, Windows PowerShell

Feed for the post RSS 2.0 Comment this post

Submit comment

CAPTCHA Image CAPTCHA Audio
Refresh Image