user2166059
user2166059

Reputation: 35

Format multiple USB drives in powershell

New to powershell and trying to figure out how to format all attached usb drives. The following code prompts for a drive letter during format, keeps iterating by one and won't escape that assign drive letter prompt.

foreach ($usbDrive in get-disk)
{
if ($usbDrive.bustype -eq 'usb')
    {
     Format-Volume -FileSystem FAT32    
    }
}

This code seems to work but it prompts for more usb drives than are plugged in. If it's possible, I'd like to have the drive keep the same letter and skip the prompt.

foreach ($usbDrive in get-disk | where bustype -eq 'usb'){Format-Volume -FileSystem FAT32}

Upvotes: 0

Views: 614

Answers (1)

Marios
Marios

Reputation: 161

I was working on something similar today and i created this script with a prompt to avoid formatting any unwanted drive:

$flashDrives = (get-volume | Where-Object { $_.drivetype -eq 'removable' })

foreach ($flashDrive in $flashDrives) {
    $title = 'Format Drive?'
    $message = 'Do you want to format ' + $flashDrive.FileSystemLabel + ' (' + $flashDrive.DriveLetter + ':) ' + 'with file system "' + $flashDrive.FileSystemType + '" ?'

    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
        "Format drive."

    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
        "Skip drive."

    $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

    $result = $host.ui.PromptForChoice($title, $message, $options, 0)

    switch ($result) {
        0 { Format-Volume -DriveLetter $flashDrive.DriveLetter -FileSystem FAT32 }
        1 { "Skipping drive" }
    }
}

If you really want to format without any prompts you can remove the prompts at your own risk!

Upvotes: 1

Related Questions