怎样用脚本批量格式化U盘?

wen 实用脚本 2

本文目录导读:

怎样用脚本批量格式化U盘?

  1. 方法1:Windows PowerShell脚本
  2. 方法2:Windows批处理脚本
  3. 方法3:Python脚本(跨平台)
  4. 方法4:Linux Shell脚本
  5. 使用注意事项

我来详细介绍几种批量格式化U盘的方法:

方法1:Windows PowerShell脚本

# batch_format_usb.ps1
$drives = Get-WmiObject Win32_LogicalDisk | Where-Object {$_.DriveType -eq 2}
foreach ($drive in $drives) {
    $driveLetter = $drive.DeviceID
    Write-Host "正在格式化 $driveLetter ..."
    # 格式化命令 (FAT32格式,快速格式化)
    $formatResult = Format-Volume -DriveLetter $driveLetter.Substring(0,1) -FileSystem FAT32 -NewFileSystemLabel "USB" -Confirm:$false
    if ($?) {
        Write-Host "$driveLetter 格式化成功" -ForegroundColor Green
    } else {
        Write-Host "$driveLetter 格式化失败" -ForegroundColor Red
    }
}

方法2:Windows批处理脚本

@echo offU盘批量格式化工具
echo 正在检测U盘...
for %%a in (D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
    if exist %%a:\ (
        wmic logicaldisk where deviceid="%%a:" get drivetype | findstr "2" >nul
        if errorlevel 1 (
            echo 格式化U盘 %%a:
            format %%a: /FS:FAT32 /Q /V:USB /Y
            if !errorlevel! equ 0 (
                echo %%a: 格式化成功
            ) else (
                echo %%a: 格式化失败
            )
        )
    )
)
echo 格式化完成!
pause

方法3:Python脚本(跨平台)

import os
import subprocess
import sys
import platform
def list_usb_drives():
    """列出系统中的U盘"""
    usb_drives = []
    if platform.system() == "Windows":
        # Windows下检测U盘
        import win32api
        import win32file
        drives = win32api.GetLogicalDriveStrings().split('\0')[:-1]
        for drive in drives:
            drive_type = win32file.GetDriveType(drive)
            if drive_type == win32file.DRIVE_REMOVABLE:  # 可移动磁盘
                usb_drives.append(drive)
    elif platform.system() == "Linux":
        # Linux下检测U盘
        result = subprocess.run(['lsblk', '-o', 'NAME,TYPE,MOUNTPOINT', '-ln'], 
                              capture_output=True, text=True)
        lines = result.stdout.split('\n')
        for line in lines:
            if 'disk' in line and 'sd' in line:
                parts = line.split()
                if len(parts) >= 2:
                    usb_drives.append(f"/dev/{parts[0]}")
    elif platform.system() == "Darwin":  # macOS
        result = subprocess.run(['diskutil', 'list', 'external'], 
                              capture_output=True, text=True)
        # 解析macOS的磁盘列表
        lines = result.stdout.split('\n')
        for line in lines:
            if '/dev/disk' in line:
                parts = line.split()
                if parts:
                    usb_drives.append(parts[0])
    return usb_drives
def format_usb(drive_path, filesystem='FAT32', label='USB'):
    """格式化U盘"""
    print(f"正在格式化: {drive_path}")
    if platform.system() == "Windows":
        # Windows格式命令
        drive_letter = drive_path[0]
        cmd = f"format {drive_letter}: /FS:{filesystem} /Q /V:{label} /Y"
    elif platform.system() == "Linux":
        # Linux格式命令
        cmd = f"sudo mkfs.{filesystem.lower()} -n {label} {drive_path}"
    elif platform.system() == "Darwin":  # macOS
        cmd = f"diskutil eraseDisk {filesystem} {label} MBR {drive_path}"
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=300)
        if result.returncode == 0:
            print(f"✓ {drive_path} 格式化成功")
            return True
        else:
            print(f"✗ {drive_path} 格式化失败: {result.stderr}")
            return False
    except subprocess.TimeoutExpired:
        print(f"✗ {drive_path} 格式化超时")
        return False
    except Exception as e:
        print(f"✗ {drive_path} 格式化出错: {e}")
        return False
def main():
    print("=== U盘批量格式化工具 ===")
    print("正在检测U盘...")
    usb_drives = list_usb_drives()
    if not usb_drives:
        print("未检测到U盘,请插入U盘后重试")
        return
    print(f"发现 {len(usb_drives)} 个U盘:")
    for i, drive in enumerate(usb_drives):
        print(f"{i+1}. {drive}")
    confirm = input("\n是否格式化所有U盘?(y/n): ")
    if confirm.lower() != 'y':
        print("操作已取消")
        return
    # 格式化所有U盘
    success_count = 0
    fail_count = 0
    for drive in usb_drives:
        if format_usb(drive, filesystem='FAT32', label='USB'):
            success_count += 1
        else:
            fail_count += 1
    print(f"\n格式化完成!成功: {success_count}, 失败: {fail_count}")
if __name__ == "__main__":
    main()

方法4:Linux Shell脚本

#!/bin/bash
# batch_format_usb.sh
# 检测U盘设备
echo "正在检测U盘..."
usb_devices=($(lsblk -o NAME,TYPE | grep 'disk' | grep -E 'sd[b-z]' | awk '{print $1}'))
if [ ${#usb_devices[@]} -eq 0 ]; then
    echo "未检测到U盘"
    exit 1
fi
echo "发现 ${#usb_devices[@]} 个U盘:"
for dev in "${usb_devices[@]}"; do
    echo "/dev/$dev"
done
read -p "是否格式化所有U盘?(y/n): " confirm
if [ "$confirm" != "y" ]; then
    echo "操作已取消"
    exit 0
fi
# 格式化U盘
for dev in "${usb_devices[@]}"; do
    device="/dev/$dev"
    echo "正在格式化 $device ..."
    # 卸载分区
    umount ${device}* 2>/dev/null
    # 格式化 (FAT32格式)
    sudo mkfs.fat -F32 -n "USB" $device
    if [ $? -eq 0 ]; then
        echo "$device 格式化成功"
    else
        echo "$device 格式化失败"
    fi
done
echo "格式化完成!"

使用注意事项

Windows脚本使用:

  1. 以管理员身份运行 PowerShell 或命令提示符
  2. 对于PowerShell脚本,可能需要先执行:Set-ExecutionPolicy RemoteSigned
  3. 确保U盘已正确插入,且没有重要数据

Python脚本使用:

  1. 安装依赖:pip install pywin32 (Windows)
  2. Linux/Mac需要root权限sudo python3 script.py

安全建议:

  1. 备份数据:格式化会清除所有数据
  2. 确认设备:确保脚本不会误格式化系统盘
  3. 测试环境:先在单个U盘上测试
  4. 添加保护:建议检查磁盘大小和类型,避免格式化系统盘

需要我详细解释某个脚本的特定部分,或添加其他功能(如选择性格式化、进度显示等)吗?

抱歉,评论功能暂时关闭!