使用自动运行为驱动器分配字母

使用自动运行为驱动器分配字母

我有一个外部驱动器,由于不可避免的原因,无论我将其插入哪台计算机,都需要为其分配相同的字母。我认为这可以通过 Diskpart 脚本来实现。我知道分区的 GUID,但是如何使用 GUID 在 Diskpart 中选择硬盘?或者是否有其他方法可以使用脚本为硬盘分配字母?

答案1

这是我编写的将卷号更改为 K 的批处理文件。如能提供任何有助于增强代码的帮助,我将不胜感激。

PS. 开头有一部分代码是使用管理员权限运行的。我故意省略了这部分。

:mainBody
set "volume=\Volume{8bc9f784-9f15-11e4-be58-a60f30d14122}"
set "drive="

for %%D in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
mountvol %%D: /L | findstr "%volume%" >nul
if not errorlevel 1 (
if %%D==K (
echo DONE!
goto end
) else (
set "drive=%%D"
goto clearK
)
)
)

:clearK
mountvol K: /L >nul
if errorlevel 1 (
echo K: is free...
) else (
echo K: is taken...
for /f "tokens=1 delims=" %%A in ('mountvol K: \L') do SET currdriveguid=%%A
for %%D in ( Z Y X W V U T S R Q P O N M L K J H G F E D B A ) do (
mountvol %%D: /L >nul
if errorlevel 1 (
mountvol K: /d
mountvol %%D:\ currdriveguid
echo Current Volume moved to %%D:...
goto assignK
)
)
)


: assignK
if not defined drive (
mountvol K:\ \\?%volume%\
) else (
mountvol %drive%: /D
mountvol K:\ \\?%volume%\
)

:end

答案2

我还编写了一个 Powershell 脚本来执行同样的工作。Powershell 比批处理脚本做得更好。

$driveI = Get-WmiObject -Class win32_volume -Filter "DriveLetter='I:'"

if ($driveI -eq $null)  {

    write-host "I: is free..."

}   elseif ($driveI.DeviceID.Contains("7899c0f7-f556-11e4-9cf2-7071bc4ab2b5") -And  "$drive.SerialNumber = '-1675536360'")    {

    write-host "I: is already assigned to the required disk..."
    Write-Host "Press any key to continue ..."
    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit

}   else    {    
    write-host "I: is occupied..."
    foreach ( $s in @("'Z:'", "'Y:'", "'X:'", "'W:'", "'V:'", "'U:'", "'T:'", "'R:'", "'Q:'", "'P:'", "'O:'", "'N:'", "'M:'", "'L:'", "'K:'", "'J:'", "'H:'", "'G:'", "'F:'", "'E:'", "'D:'", "'B:'", "'A:'"))
    {
        $testdrv = Get-WmiObject -Class win32_volume -Filter "DriveLetter=$s"

        if ($testdrv -eq $null)
        {
            $s = $s.Trim([char]0x0027)
            Set-WmiInstance -input $driveI -Arguments @{DriveLetter=$s}
            Write-Host I: has been moved to $s
            break
        }
    }
}

$diary = Get-WmiObject -Class win32_volume -Filter "Label='My Diary'"
if ($diary.DeviceID.Contains("7899c0f7-f556-11e4-9cf2-7071bc4ab2b5") -And  "$diary.SerialNumber = '-1675536360'")
{
    Set-WmiInstance -input $diary -Arguments @{DriveLetter="I:"}
    Write-Host "Press any key to continue ..."
    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit

}   else    {

    Write-Host Error Occured!
    Write-Host "Press any key to continue ..."
    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit
}

相关内容