Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Created December 31, 2020 14:21
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 IISResetMe/6facb638e58831cc0b6737de6cb9d05c to your computer and use it in GitHub Desktop.
Save IISResetMe/6facb638e58831cc0b6737de6cb9d05c to your computer and use it in GitHub Desktop.
Quote repeatable command invocation from [InvocationInfo] for simple parameter types
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
}
. $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