How do I loop through guid generation a specific number of times?

Viewed 182

I put together this script from various sources to generate a guid, but now I want to loop this so it will generate and output 10 results:

$Guid = [guid]::NewGuid()
$Password = [string]$Guid
$Password = $Password.Replace("-", "")
Clear-Host
$Password
Clear-Variable -Name "Guid"
Clear-Variable -Name "Password"
3 Answers

The below will do what you need.

I am initializing the loop then using the New-Guid function instead of [guid]::NewGuid() then converting it to a string and replacing the - with nothing

for($i=1; $i -le 10; $i++){
    (New-Guid).Guid.tostring().Replace("-", "")
}

Please read up on for loops here so you can change it where necessary

1..4 |  % { [System.Guid]::NewGuid() }

You don't really need to use .Replace to remove the hyphens from a new Guid instance, simply calling the Guid.ToString method with the N format will do that for you:

$guids = 0..9 | ForEach-Object { [guid]::NewGuid().ToString('N') }
Related