ThisIsWin11 icon indicating copy to clipboard operation
ThisIsWin11 copied to clipboard

Curly quotes may break PowerShell depending on version

Open mavaddat opened this issue 3 years ago • 0 comments

https://github.com/builtbybel/ThisIsWin11/blob/2072bc9598002aeb8c070ec70a9b26781bb26e27/src/TIW11/Views/AppsWindow.cs#L293-L294

Some versions of PowerShell may not parse with curly quotation marks. Please see https://4sysops.com/archives/dealing-with-smart-quotes-in-powershell/:

It works, but only because PowerShell converts the smart quotes to "normal” quotes. You could just be OK with this, but there are times when these "smart" quotes become a problem. Running on different PowerShell versions, code consumed by other applications, and other factors are all culprits of the problem. The system does not interpret these smart quotes the same 100% of the time.

It's always best to dumb down these smart quotes by replacing them. To replace text in PowerShell, I typically use -replace like this: $string -replace 'replacethis','withthis'. This means all we have to do is find these smart quotes and then just replace them with good ol' fashioned quotes, right? No. Unfortunately, there's no smart quote character on your keyboard. Instead, we have to define those characters via a character map. Smart double quotes use both \u201D and \u201C while \u2019 and \u2018 represent single smart quotes. We need to look for and replace these characters.

To make this replacement easier, we can create a couple regular expressions and assign them to variables.

$smartSingleQuotes = '[\u2019\u2018]'
$smartDoubleQuotes = '[\u201C\u201D]'

Once we've defined those, we can now search any text file for these characters and replace them with "normal" single and double quotes using Get-Content and the -replace operator.

$filePath = 'C:\test.ps1'
$content = Get-Content -Path $filePath -Raw
$content = $content -replace $smartSingleQuotes,"'"
$content -replace $smartDoubleQuotes,'"' | Set-Content -Path $filePath

We can then look at our original text file (a script in this case) and see our script has replaced all instances of double and single smart quotes as we expect!

mavaddat avatar Jan 22 '22 02:01 mavaddat