PowerShell - Writing a new GUID for a board with curly braces

Viewed 244

I start with powershell, and I wrote a small and simple code that writes a new GUID to the board.

I used this line:

Set-Clipboard (New-Guid).Guid

It works, but I could not find how to write the GUID with curly brackets.

Surely there are already answers on the subject, but I had a hard time finding.

Maybe give someone an idea?

Thank you!

2 Answers

Subexpression operator $( ) allows to resolve the expression embedded in the string.

Note that calling the .Guid property of the object is not needed in this case since the string representation of it resolves to the 32 digits separated by hyphens, same as .ToString() or .ToString('D').

Set-Clipboard "{$(New-Guid)}"
# `$(New-Guid)` is evaluated first then the result of the expression
# is embedded in the string.

zett42's helpful comment provides a much better alternative to the one above simply by using Guid .ToString(String) Method with the "B" format parameter:

Set-Clipboard (New-Guid).ToString('B')

Code

$guid = [System.Guid]::NewGuid().ToString("B")
Write-Host $guid
Set-Clipboard $guid
$guid = "{$([System.Guid]::NewGuid())}"
Write-Host $guid
Set-Clipboard $guid
$guid = "{$((New-Guid).Guid)}"
Write-Host $guid
Set-Clipboard $guid
$guid = (New-Guid).Guid
Write-Host "{$guid}"
Set-Clipboard "{$guid}"

Output
guid


Alternative implementation / Cryptographic Guid

function New-CryptoGuid {
        $bytes = [System.Security.Cryptography.RandomNumberGenerator]::GetBytes(16)
        return [System.Guid]::new($bytes).ToString("B")
}

$guid = New-CryptoGuid
Write-Host $guid
Set-Clipboard $guid

Output
crypto guid


References

System.Guid
Guid.NewGuid Method - Remarks
System.Guid - Constructor
RandomNumberGenerator.GetBytes Method

Related