我正在尝试编写PowerShell脚本,以将I:的驱动器号更改为其他名称。这是脚本。
$driveI = Get-WmiObject -Class win32_volume -Filter "DriveLetter='I:'"
if ($driveI.SerialNumber=""){
write-host "I: is free..."
} 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 (!$testdrive.Exist)
{
$s = '"'+$s.Trim([char]0x0027)+'"'
Set-WmiInstance -input $driveI -Arguments @{DriveLetter=$s}
Write-Host I: has been moved to $s
break
}
}
}
请允许我引导您完成脚本。
$driveI
用于检索有关I:的所有信息。现在,如果I:没有序列号,则表明I:不存在。另一方面,如果I:存在,那么我正试图找到一个免费的驱动器号。我正在使用
foreach
循环实现搜索。现在,当我们调用Get-WmiObject
时,我们使用带单引号的驱动器号。但是,当我们使用Set-WmiInstance
时,我们使用双引号。但是,即使我将$s
修改为用双引号引起来,它也不起作用。简而言之,如果我使用
Write-Host $s
,我将获得输出,例如"E:"
。当我使用Set-WmiInstance -input $driveI -Arguments @{DriveLetter="E:"}
时,它可以工作。但是当我使用Set-WmiInstance -input $driveI -Arguments @{DriveLetter=$s}
时,它不起作用。谁能告诉我我在做什么错? 最佳答案
无论如何,当以后要删除引号时,请不要在字符串中加上引号。而是在您实际需要的地方添加引号:
$driveLetters = 'Z:', 'Y:', 'X:', ..., 'D:', 'B:', 'A:'
foreach ( $s in $driveLetters ) {
$testdrv = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter='$s'"
if (-not $testdrv) {
Set-WmiInstance -input $driveI -Arguments @{DriveLetter=$s}
Write-Host "I: has been moved to $s"
break
}
}
关于string - 在Powershell中将字符串变量作为参数传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30172099/