openCivilisation
openCivilisation

Reputation: 936

Powershell guid is not unique when I run it in multiple threads - How can I make it unique?

I am running a script in powershell in multiple threads (multiple shells), and I'm finding that its possible for the NewGuid powershell function to generate values in powershell 7 that are not actually unique when run at the same time.

"${env:TEMP}\some_unique_file_$([guid]::NewGuid()).json"

The above can produce a conflict when I'd like each string here to be unique. Is there something missing or is this a bug? It's almost as if PID is not considered when generating a GUID.

for further context, its also possible because its defined as a parameter default, that this is causing the issue:

param (
    [Parameter(Mandatory = $false)] [string]$houdiniEnvFile = "${env:TEMP}\some_unique_file_$([guid]::NewGuid()).json"
)

Upvotes: -2

Views: 477

Answers (1)

Josua Doering
Josua Doering

Reputation: 86

Theo is right. You have to expand the property Guid. NewGuid() creates an object with a single property. And to get to the value, this single property has to be expanded.

That will look like this:

${env:TEMP}\some_unique_file_$([guid]::NewGuid().Guid).json

Another possible approach is:

${env:TEMP}\some_unique_file_$((New-Guid).Guid).json

It is as fast, but maybe a little bit easier on the eyes ;)

Upvotes: -3

Related Questions