imagine following code:
# script start $welcomemessage = "hello $username, today $($date.dayofweek)" .. .. # 100 lines of other functions , not... .. function greet-user { $username = get-usernamefromsomewherefancy $date = get-datefromsomewherefancy $welcomemessage } this basic example, tries show script there $welcomemessage person running script can set @ top of script , controls how/what message displayed is.
first thing's first: why this? well, if you're passing script around multiple people, might want different messages. maybe don't $($date.dayofweek) , want full date. maybe don't want show username, whatever.
second, why put @ top of script? simplicity. if have 1000 lines in script , messages these spread on script, makes nightmare people find , change these messages. static messages, in form of localized strings , stuff, nothing new, except variable parts in it.
so, issue. if run code , invoke greet-user (assuming functions/cmdlets retrieving username , date exist , return proper...) greet-user return hello , today is.
this because string expanded when declare it, @ top of script, when neither $username nor $date objects have value.
a potential workaround create strings single quotes, , use invoke-expression expand them. because of spaces, gets bit messy. i.e.:
$welcomemessage = 'hello $env:username' invoke-expression $welcomemessage this throws error because of space, work have declared such:
$welcomemessage = 'hello $env:username' $invokeexpression = "`"$welcomemessage`"" messy...
also, there's problem in form of code injection. since we're allowing user write own welcome message no bounds specified, what's prevent them putting in like...
$welcomemessage 'hello $([void] (remove-item c:\windows -force -recurse))' (yes, know not delete example)
granted script , if can modify string can modify else on script, whereas example gave maliciously taking advantage of nature of script, can happen accidentally puts in string ends having unwanted consequences.
so... there's got better way without use of invoke-expression, can't quite thing of 1 appreciated :)
embedding variables strings not way create dynamic text, way this:
$welcomemessage = 'hello {0}, today {1}' # 100 lines of other functions , not... function greet-user { $username = get-usernamefromsomewherefancy $date = get-datefromsomewherefancy $welcomemessage -f $username, $date }
Comments
Post a Comment