0

I have trouble with following piece of code:

$result = "F651F545A059588ABFDCE7EE3EEB27EED8CED28D"
winrm create winrm/config/Listener?Address=*+Transport=HTTPS '@{Hostname="my.host.winagent"; CertificateThumbprint="$result"}'

it yields:

Message = The WS-Management service cannot process the configuration request because the certificate thumbprint in the request is not a valid hex string: $result.

it looks like variable result is not being expanded, probably because it is inside array? How to get the variable value expanded there?

Wojtas.Zet
  • 636
  • 2
  • 10
  • 30
  • 2
    Type the command into powershell and the syntax highlighter will show you the difference between using `'` and `"`. – msanford Nov 19 '21 at 15:10
  • Try removing the single quotes. – Santiago Squarzon Nov 19 '21 at 15:14
  • In short: Only `"..."` strings (double-quoted) perform string interpolation (expansion of variable values) in PowerShell, not `'...'` strings (single-quoted): see [this answer](https://stackoverflow.com/a/40445998/45375) for an overview of PowerShell's _expandable strings_ (interpolating strings) and [this answer](https://stackoverflow.com/a/55614306/45375) for an overview of PowerShell string literals in general. – mklement0 Nov 19 '21 at 18:08
  • @Santiago, not quoting the argument would cause PowerShell to parse it as a regular hashtable, whose `.ToString()` stringification would then be passed (because an _external program_ is being called), (uselessly) resulting in verbatim `System.Collections.Hashtable` getting passed. – mklement0 Nov 19 '21 at 18:11
  • @mklement0 I was just following an example from [this link](https://support.solarwinds.com/SuccessCenter/s/article/Create-a-WinRM-HTTPS-listener?language=en_US) where it seems it works passing an actual hashtable, it was more of a trial an error comment from my side. – Santiago Squarzon Nov 19 '21 at 18:15
  • 1
    I see, @Santiago, but the linked article's commands were written for cmd.exe. The behavior I describe is a pitfall, so much so that core members of the PowerShell team, many years ago, pondered making an exception for passing such hashtable-like arguments, but decided against it - see [GitHub issue #1761](https://github.com/PowerShell/PowerShell/issues/1761). You can demonstrate that it doesn't work via the following commands: `cmd /c echo @{ foo = 1 }` (Windows) and `/bin/echo @{ foo = 1 }` (Unix) – mklement0 Nov 19 '21 at 19:38
  • Guys, thank you all for your input. It gave some more insight how it works. I am accepting answer below. – Wojtas.Zet Nov 22 '21 at 12:53

1 Answers1

2

You need to use " (not ') to create an expandable string literal - escape the literal "'s by doubling them:

winrm create winrm/config/Listener?Address=*+Transport=HTTPS "@{Hostname=""my.host.winagent""; CertificateThumbprint=""$result""}"
Doug Maurer
  • 8,090
  • 3
  • 12
  • 13
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206