Created
December 31, 2020 14:21
-
-
Save IISResetMe/6facb638e58831cc0b6737de6cb9d05c to your computer and use it in GitHub Desktop.
Quote repeatable command invocation from [InvocationInfo] for simple parameter types
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
function Get-InvocationQuote | |
{ | |
param([System.Management.Automation.InvocationInfo]$Invocation) | |
$cmdText = $Invocation.InvocationName | |
foreach($param in $Invocation.BoundParameters.GetEnumerator()){ | |
$name = $param.Key | |
$value = switch($param.Value){ | |
{$_ -is [string]} { | |
# Quote and escape all string values as sigle-quoted literals | |
"'{0}'" -f [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($_) | |
} | |
{$_ -is [datetime]} { | |
# Quote datetime using a culture-independent format | |
"'{0}'" -f $_.ToString('o') | |
} | |
{$_ -is [bool] -or $_ -is [switch]} { | |
# Map booleans to their respective automatic variables | |
'${0}' -f "$_" | |
} | |
{$_ -is [enum] -or $_.GetType().IsPrimitive} { | |
# Leave numerals | |
$_ | |
} | |
default { | |
throw "Unable to quote '{0}' of type '{1}'" -f [System.Management.Automation.LanguagePrimitives]::ConvertTypeNameToPSTypeName($_.GetType.FullName) | |
return | |
} | |
} | |
$cmdText += " -${name}:${value}" | |
} | |
return $cmdText | |
} |
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
. $PSScriptRoot\Get-InvocationQuote.ps1 | |
function Test-Quoting { | |
param( | |
[int]$Number, | |
[string]$String, | |
[switch]$Flag, | |
[datetime]$Date | |
) | |
Get-InvocationQuote $MyInvocation | |
} | |
# Quote | |
Test-Quoting -Number 123 -String "this will'need escaping" -Date 1/1/1970 -Flag | |
# Repeat and compare with | |
Test-Quoting -Number 123 -String "this will'need escaping" -Date 1/1/1970 -Flag |Invoke-Expression |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment