Created
May 16, 2019 00:47
-
-
Save Brad-Christie/4654e2b3d18d330c14475af4d227c115 to your computer and use it in GitHub Desktop.
How to parse and format a string with placeholders, and only bring in the tokens you want.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$Make = "Tesla" | |
$Model = "X" | |
$Year = 2017 | |
$Format = "`$Year `$Make `$Model" | |
Function Format-UnsafeString { | |
Param( | |
[Parameter(Position = 0, Mandatory)] | |
[string]$Format | |
, | |
[Parameter()] | |
[string]$Make = "Ford" | |
, | |
[Parameter()] | |
[string]$Model = "Mustang" | |
) | |
Process { | |
$ExecutionContext.InvokeCommand.ExpandString($Format) | |
} | |
} | |
Function Format-SafeString { | |
Param( | |
[Parameter(Position = 0, Mandatory)] | |
[string]$Format | |
, | |
[Parameter()] | |
[string]$Make = "Ford" | |
, | |
[Parameter()] | |
[string]$Model = "Mustang" | |
) | |
Begin { | |
$Powershell = [powershell]::Create() | |
} | |
Process { | |
$Powershell = [Powershell]::Create() | |
[void]$Powershell.AddScript($scriptBlock) | |
[void]$Powershell.AddParameter("_", "`${Make} `${Model}") | |
[void]$Powershell.AddParameter("Make", $Make) | |
[void]$Powershell.AddParameter("Model", $Model) | |
Return $Powershell.Invoke() | |
} | |
End { | |
$Powershell.Dispose() | |
} | |
} | |
# Will include Year, but we don't want it to | |
# ExecutionContext is aware of $Year declared above | |
Format-UnsafeString $Format -Make "Jeep" -Model "Wrangler" | |
# Will NOT include year (sandboxed) | |
# ExectionContext is running within the confines of the sandbox | |
Format-SafeString $Format -Make "Jeep" -Model "Wrangler" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment