Skip to content

Instantly share code, notes, and snippets.

@Brad-Christie
Created May 16, 2019 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Brad-Christie/4654e2b3d18d330c14475af4d227c115 to your computer and use it in GitHub Desktop.
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.
$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