PowerTip: Use PowerShell to Generate Random File Name


Summary: Use Windows PowerShell to generate a random file name.

Hey, Scripting Guy! Question How can I use Windows PowerShell to generate a random file name so I can ensure that
           a file I create does not have a naming conflict?

Hey, Scripting Guy! Answer Use the GetRandomFileName static method from the System.IO.Path .NET Framework
           class, for example:

[System.IO.Path]::GetRandomFileName()

Comments (5)

  1. jrv says:

    That;s cheating. That is not even writing code. That is just copying things from the book.

    😉 (:>

    Try this as it gives a much better file and puts the file in the correct place.

    [System.IO.Path]::GetTempFileName()

    The random stuff just gives a name with no help and, as my friends like to say, "no joy".

    Reminder! Spring ahead this week!

  2. tommymaynard says:

    It’s things like this you hope you don’t forget when the time comes around where you need it. Here’s a quick modification to dump the file extension, which may be helpful: ([System.IO.Path]::GetRandomFileName()).Split(‘.’)[0]

  3. romeo says:

    random name doesn’t necessary mean unique. An indirect proportion exist between the chance to be unique and the name’s length.

  4. AllanM says:

    $file = $env:temp + "" + (get-date -uformat %s)
    returns e.g. C:UsersAllanMAppDataLocalTemp1425570061.58076

    This returns a file name in the users temp directory, using the current timestamp in Unix %s format – seconds since Epoch.

Skip to main content