Link to home
Create AccountLog in
Avatar of tomdenton
tomdenton

asked on

vbscript to format USB drive and set label

Hi,

I need a simple vbs to format and set the drive label of a usb. I found this but it does not seem to do anything on Win8. Any suggestions please?
Tom

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colVolumes = objWMIService.ExecQuery _
("Select * from Win32_Volume Where Name = 'E:\\'")

For Each objVolume in colVolumes
errResult = objVolume.Format("NTFS", true)
objVolume.Label = "MyLabel"
Next

Open in new window

Avatar of x-men
x-men
Flag of Portugal image

the script assumes drive E: for the usb. is this correct?
Avatar of tomdenton
tomdenton

ASKER

Yes but that can be changed to anything as needed
what's returne on the errResult variable?
nothing seems to happen at all format wise and the labels is not changed either
Try removing the double "\"...with this adjustment:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colVolumes = objWMIService.ExecQuery _
("Select * from Win32_Volume Where DriveType=3)

For Each objVolume in colVolumes
  If objVolume.Name = "E:\" Then  'Filters for ONLY drive E:
    errResult = objVolume.Format("NTFS", true)
    objVolume.Label = "MyLabel"
  End If
Next

Open in new window

Also - are you running this in an elevated environment? (as Administrator)
yes i am full admin - (out now will test later)
But from an elevated environment?
For instance, launching your app using
cscript FormatUSB.vbs

Open in new window

in a command prompt...does the command window state that it's an Administrative environment?

See: http://www.eightforums.com/tutorials/2754-elevated-command-prompt-open-windows-8-a.html
Since the suggested change i get an 'unterminated string constant' error on line 6

and the same if run as cscript... from a cmd window

the command window does not specifically stat admin environment. I can however run lots of other scripts without a problem if that helps?!
i went back to my original script and ran that from an admin cmd and it ran and formatted the drive ok but did not rename its label

Will it be possible to make this work from a non admin point of view though?
ASKER CERTIFIED SOLUTION
Avatar of sirbounty
sirbounty
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
This works fine if 'elevated'. The other option is i can compile it using exescript then right click and run as admin.

Thanks for your help
Happy to help - thanx for the grade! :^)