Generate GUID in Windows with batch file
Asked Answered
V

11

66

How can I generate a GUID in a batch file running using the commandline in Windows?

Valenciavalenciennes answered 30/11, 2010 at 11:54 Comment(4)
There is no built-in command available that does that. Either write your own, or get an existing one.Leonardo
BTW, MS-DOS has been dead for at least 10 years. The program that runs batch files is the command prompt.Leadbelly
#570358Fusty
@Tim Robinson : Thanks for your input, looking forward for help on creating GUIDs.Valenciavalenciennes
L
89

The Windows SDK comes with a tool called uuidgen (if you have Visual Studio, you'll have the Windows SDK, and you need to run the Visual Studio Command Prompt to set proper paths).

C:\>uuidgen

This will output a new GUID, e.g.

cc23b318-156e-473f-aa6e-517bf091a0f0

Leadbelly answered 30/11, 2010 at 11:57 Comment(8)
Maybe download and install the Windows SDK separately? Although it's a lot for one utility - it would be quicker to write your own than to wait for the download.Leadbelly
incases where i can't download due to some reasons what can be another alternative than SDKValenciavalenciennes
If you have no other alternative you'll probably need to write your own GUID generatorLeadbelly
You need to use the -c option on uuidgen for a windows installer project file.Melitamelitopol
Funny thing, I have three different versions of VS but uuidgen was not in the PATH for me. Also, it doesn't seem to be really random but time-based (Unix versions of this utility have a -r and -t flags to specify if you want it random-based or time-based.Schuster
Can I store it on a batch variable?Appurtenant
IN VS2022 command prompt it's called guidgenAlbin
This should not be marked correct, as most users do not have the SDK. Calling powershell from cmd is the way to go, as various answers below describe.Basham
A
33

Try this if you have powershell environment.

FOR /F %a IN ('POWERSHELL -COMMAND "$([guid]::NewGuid().ToString())"') DO ( SET NEWGUID=%a )

Then ready Guid value from %NEWGUID%

Anneliese answered 31/5, 2013 at 18:52 Comment(2)
If writing a batch file (.bat), don't forget to double the % in the FOR statement (so the line should read FOR /F %%a IN ('POWERSHELL -COMMAND "$([guid]::NewGuid().ToString())"') DO ( SET NEWGUID=%%a ))Nightlong
@Soundararajan powershell and .NET is available in all Windows versions since VistaImpoverished
S
30

easy to do in powershell

[guid]::NewGuid()
Sumatra answered 14/11, 2016 at 14:20 Comment(1)
Even easier now: New-GuidChild
C
26

1.Create a file named myuuid.vbs with the content

set obj = CreateObject("Scriptlet.TypeLib")  
WScript.StdOut.WriteLine Mid(obj.GUID, 2, 36)

2.goto command prompt

cscript //NoLogo myuuid.vbs

Using JAVA code

    UUID uuid = UUID.randomUUID();
    String randomUUIDString = uuid.toString();
Casimiracasimire answered 30/11, 2010 at 11:59 Comment(5)
@Valenciavalenciennes this is VB Script code that will do your task you don't need any special env for this just follow 2 steps mentionedCasimiracasimire
@Valenciavalenciennes have you followed step 2 exactly mentioned ? from command line it should be "script //NoLogo myuuid.vbs "Casimiracasimire
@Valenciavalenciennes type "cscript //NoLogo myuuid.vbs"Casimiracasimire
@Valenciavalenciennes devguru.com/technologies/vbscript/quickref/… here is example how to create file using VBS and it is already stored in variable OBJ , I am not much aware about VBS otherwise I would have told you :)Casimiracasimire
Install cygwin, and ensure you have the util-linux package. That will give you a uuidgen command.Budbudapest
A
13

This will copy a new GUID to your clipboard:

POWERSHELL -c "[guid]::NewGuid().ToString().ToUpper()" | CLIP

Recent versions have cmdlets like this:

POWERSHELL -c "New-Guid | Set-Clipboard"
Antilogy answered 10/4, 2018 at 11:46 Comment(0)
L
11

There is no built-in command available that does that. Either write your own, or get an existing one.

A simple program that outputs a GUID to the console could be written using C#:

class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine(System.Guid.NewGuid().ToString());
    }
}

Place the above snippet in a file name guidgen.cs and then compile it using the following command line (.NET Framework 2.0 would have to be installed on your system):

%WINDIR%\Microsoft.NET\Framework\v2.0.50727\csc.exe guidgen.cs 

This will create an executable named guidgen.exe.

Leonardo answered 30/11, 2010 at 12:0 Comment(5)
seems like C#. well i have an very old pc with no .NET framwork will this work or do you some solution other than this ?Valenciavalenciennes
@Pratik: How old? Is it really running MS-DOS? Do you have any compiler available at all?Leonardo
dos version 5.1.2600 on Windows XP. i don't have any idea about compilersValenciavalenciennes
Any idea why I'm not able to clip the output in bash as $ guidgen | clip? I'm having to wrap this in a function and export it as guidgen() { echo "$(guidgen.exe)"; } export -f guidgen (see #1500999).Substratosphere
The ToString call is not necessary as WriteLine has an overload for System.Object, which does the same. Not sure if creating the string instance is worse than boxing performance-wise, but it certainly is longer and less readable.Tiossem
T
5

If you want to do it with pure cmd commands, you can use something like that (this is not a true GUID but it can help depending on your context) :

@call :GetGuid NewGuid
@echo My new GUID : %NewGuid%

@goto :eof


:GetGuid
 @set _guid=%computername%%date%%time%
 @set _guid=%_guid:/=%
 @set _guid=%_guid:.=%
 @set _guid=%_guid: =%
 @set _guid=%_guid:,=%
 @set _guid=%_guid::=%
 @set _guid=%_guid:-=%
 @set %1=%_guid%
@goto :eof
Thieve answered 1/11, 2013 at 15:31 Comment(4)
Save the contents as a .BAT file and run it. Works on my machine (Windows 8).Auspice
Better to do it in a .CMD file to be interpreted by CMD.EXE instead of COMMAND.COM ;-) differencebetween.net/technology/difference-between-cmd-and-batThieve
why don't just put @echo off at the beginning instead of prefixing every commands with @?Impoverished
Prefixing every commands with a @ is useful when you are debugging your script. If you suspect that a line is not running well, just suppress the @ for this line and re-run your script. You will see at the console what's happening.Thieve
P
4

try with uuid.bat Without arguments it will just echo the generated uuid:

c:\>uuid.bat

2186cb38-d649-4c99-b7cc-c505e4dae9c2

If argument is passed it will be stored in a variable with the same name:

call uuid.bat my_uuid
echo %my_uuid%

94772f66-8bca-468e-9e9a-de0d9ee05cc1

For windows formatted GUIDs you can use guid.bat:

for /f %a in ('guid.bat') do set guid=%a
echo %guid%
Pinard answered 13/6, 2020 at 6:40 Comment(0)
A
2

If you have dotnet installed:

$ dotnet tool install -g guid
$ guid
bf4be9d0-7d1b-485c-a435-d07fd7b892f0
$ guid help
Usage:

    guid [option]

Where [option] is an optional single character that controls formatting:

    N    B382C3F44E604D08B48A2D342A659B4E
    D    B382C3F4-4E60-4D08-B48A-2D342A659B4E
    B    {B382C3F4-4E60-4D08-B48A-2D342A659B4E}
    P    (B382C3F4-4E60-4D08-B48A-2D342A659B4E)

When unspecified, 'd' formatting is used. Use lowercase [option] for lowercase output.
Astraphobia answered 14/12, 2020 at 9:39 Comment(0)
O
2

One could abuse bitsadmin to generate a GUID. This will be profoundly faster than calling PowerShell from a Batch script.

@echo off & setlocal

for /f "delims={}" %%I in ('bitsadmin /rawreturn /create guid') do set "GUID=%%~I"
>NUL bitsadmin /cancel {%GUID%}

echo Your new GUID is %GUID%.  Neat.

If you want to keep the surrounding braces, remove "delims={}" and replace {%GUID%} with %GUID%.

Opium answered 8/4, 2021 at 13:37 Comment(0)
C
0

If the system OS does not have Windows SDK but does have a C compiler with mingw-w64 toolchain then compile this small program to generate random GUID. Imported functions are UuidCreate (rpcrt4.lib) to create random UUID and StringFromCLSID (ole32.lib) to convert UUID to wide string.

#include <Windows.h>
#include <stdio.h>

/*
 * int UuidCreate(GUID *id);
 * int StringFromCLSID(GUID *id, wchar_t **str);
 * Libraries: Rpcrt4.lib Ole32.lib
 */

int main(void)
{
    GUID id;
    wchar_t *str = NULL;

    UuidCreate(&id);
    StringFromCLSID(&id, &str);
    wprintf(L"%ls\n", str);
}
Coronograph answered 6/8, 2019 at 4:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.