PowerShell: Get-RandomString

I’ve seen plenty of long-winded ways of getting a random string (not int) in PowerShell, but none of them seem to mention the obvious of taking a GUID, stripping of the dashes, and returning the required size. Obviously that restricts you a bit, but for my purposes, it is fine.

This is all there is to it:

function Get-RandomString ([int] $stringSize) {
    $randomString = [System.Guid]::NewGuid() -replace '-',''
    ([string] $randomString).Remove($stringSize)
}

And you call it thus…

    Get-RandomString 6

And get returned something like this:

Get-RandomString01

Here’s another way, starting off with the 1 liner, and the breaking it down a bit:

Get-RandomString02

 $randomString = ([char[]]([char]'a'..[char]'z') + 0..9 | Sort-Object {Get-Random})[0 .. 8] -join ''

 

Advertisements

SQLServer: random integers

The Rand() function in SQLServer is next to useless for anything set based

PSRandGen04

select * into t_1 from sysobjects
select rand() from t_1

I’m not going to add it in, but the addition of a seed helps not a jot.

CRYPT_GEN_RANDOM

However… CRYPT_GEN_RANDOM() is your friend (the performance overhead might need review, but  I don’t care for my use-case, which is to generate test data):

Interesting:

PSRandGen05

More interesting:

PSRandGen06.JPG

That variety gives me everything  I need, and can be also used as the basic for randomizing dates in the past and future using date arithmetic, and floats.

select * into t_1 from sysobjects

select rand(), CRYPT_GEN_RANDOM(8),
abs(convert(int,CRYPT_GEN_RANDOM(1))),
abs(convert(int,CRYPT_GEN_RANDOM(2))),
abs(convert(int,CRYPT_GEN_RANDOM(3))),
abs(convert(int,CRYPT_GEN_RANDOM(4))) from t_1

PSRandGen07