To start with a query to get of of the disks on the system would be
Get-WmiObject -Query "Select * From Win32_LogicalDisk"
You will need to limit the list to drives that you can format. The DriveType from the query will identify what type of drive and will have one of the following values:
`
Unknown (0)
No Root Directory (1)
Removable Disk (2)
Local Disk (3)
Network Drive (4)
Compact Disc (5)
RAM Disk (6)
`
See https://msdn.microsoft.com/en-us/library/windows/desktop/aa394173(v=vs.85).aspx#properties for all the wonderful info available from win32_Logicaldisk.
Now you need to choose what disks you are going to search so we will update the query return just the information we need. For just USB drives it would be
Get-WmiObject -Query "Select * From Win32_LogicalDisk Where DriveType = '2'"|select DeviceID, DriveType
For just normal disks it would be
Get-WmiObject -Query "Select * From Win32_LogicalDisk Where DriveType = '3' "|select DeviceID, DriveType
And for Both it would be
Get-WmiObject -Query "Select * From Win32_LogicalDisk Where DriveType = '2' or DriveType = '3' "|select DeviceID, DriveType
For this example I am going to use the Removable drive type of “2” so anyone who might copy and paste later code will not accidentally format a system unintentionaly. (I may or may not have done the same thing numerous times testing these types of scripts.) But you can set the query to what meets your needs.
On to the script
$drives = Get-WmiObject -Query "Select * From Win32_LogicalDisk Where DriveType = '2'"|select DeviceID, DriveType
$drives
Which gives a return on my test system of
DeviceID DriveType
-------- ---------
G: 2
H: 2
Now you want to look for the windows\system32 directory. Now the script looks like this
$drives = Get-WmiObject -Query "Select * From Win32_LogicalDisk Where DriveType = '2'"|select DeviceID, DriveType
Foreach($drive in $drives){
Write-Output "Checking $($drive.DeviceID) for \Windows\System32 "
Test-Path -Path "$($drive.DeviceID)\Windows\System32"
}
And on my test system one drive was found
Checking G: for \Windows\System32
False
Checking H: for \Windows\System32
True
Finally once you have identified the drive you can format it
$drives = Get-WmiObject -Query "Select DeviceID From Win32_LogicalDisk Where DriveType = '2'"
Foreach($drive in $drives){
$drive = $drive.DeviceID
Write-Output "Checking $drive for \Windows\System32 "
If(Test-Path -Path "$drive\Windows\System32"){
$command = @"
select Volume $drive
Clean
create partition primary
select partition 1
active
format fs=ntfs quick
active
exit
"@
$command|diskpart
If($LASTEXITCODE -gt 0)
{
Write-Output "The format of $drive failed!! Check the drive and try again!"
exit
}
Else
{
Write-Output "The format of $drive is complete"
}
}
}
You can adjust the diskpart commands to match the config you want to apply.
To run this script you must be a local admin and I strongly suggest you add additional check to ensure you do not format something you do not intend to.