I needed a quick random string for an Amazon S3 bucket name. Amazon S3 buckets share a global namespace, no two buckets can have the same name. The name I want is usually taken, so I deal with the restriction by adding a dash and six random characters to the end. Some people use GUIDs, but 366 produces over two billion combinations. Combined with the desired bucket name, uniqueness is pretty much guaranteed. (It looks a lot nicer too.)
Of course I could randomly bash the keyboard until I get a unqiue name, or I could get PowerShell to generate a random string for me. I opted for PowerShell. ;)
EDIT: Replaced System.Random
with Get-Random
.
$set = "abcdefghijklmnopqrstuvwxyz0123456789".ToCharArray()
$result += $set | Get-Random
I repeated the last command until I got the length I wanted and then I printed the result.
And here's a reusable script version.
param (
[int]$Length
)
$set = "abcdefghijklmnopqrstuvwxyz0123456789".ToCharArray()
$result = ""
for ($x = 0; $x -lt $Length; $x++) {
$result += $set | Get-Random
}
return $result
There are 2 comments.
Newer
PowerShell Prompt
Newer
PowerShell Prompt
browse with Pivot
Codility Nitrogenium Challenge
OS X Lock
HACT '13
Codility Challenges
Priority Queue
Architecture (13)
ASP.NET (2)
ASP.NET MVC (13)
Brisbane Flood (1)
Building Neno (38)
C# (4)
Challenges (3)
Collections (1)
Communicator (1)
Concurrency Control (2)
Configuration (1)
CSS (5)
DataAnnotations (2)
Database (1)
DotNetOpenAuth (2)
Entity Framework (1)
FluentNHibernate (2)
Inversion of Control (5)
JavaScript (1)
jQuery (4)
Kata (2)
Linq (7)
Markdown (4)
Mercurial (5)
NHibernate (20)
Ninject (2)
OpenID (3)
OS X (1)
Pivot (6)
PowerShell (8)
Prettify (2)
RSS (1)
Spring (3)
SQL Server (5)
T-SQL (2)
Validation (2)
Vim (1)
Visual Studio (2)
Windows Forms (3)
Windows Service (1)
Comments
grenade wrote on Thursday, 1 May, 2014 @ 6:03 PM
(char[] + 0..9 | sort {get-random})[0..12] -join ''
grenade wrote on Thursday, 1 May, 2014 @ 6:04 PM
([char[]]([char]'a'..[char]'z') + 0..9 | sort {get-random})[0..12] -join ''
Leave a Comment
Please register or login to leave a comment.