我正在尝试编写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:的所有信息。现在,如果我:没有序列号,则表示我:不存在。
另一方面,如果我:存在,我试图找到一个免费的驱动器号。我正在使用foreach
循环实现搜索。现在,当我们调用Get-WmiObject
时,我们使用单引号的驱动器号。但是当我们使用Set-WmiInstance
时,我们使用双引号。但是,即使我修改$s
被双引号包裹,它也不起作用。
简而言之,如果我使用Write-Host $s
,我会输入输出,例如"E:"
。当我使用Set-WmiInstance -input $driveI -Arguments @{DriveLetter="E:"}
时,它有效。但是当我使用Set-WmiInstance -input $driveI -Arguments @{DriveLetter=$s}
时,它无法正常工作。谁能告诉我我做错了什么?
答案 0 :(得分:3)
当你以后要移除它们时,不要将引号放在字符串中。而是在实际需要它们的地方添加引号:
$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
}
}
答案 1 :(得分:0)
它有点笨拙,但这段代码有效。我会接受你的建议,摆脱Trim
混乱。
$driveI = Get-WmiObject -Class win32_volume -Filter "DriveLetter='I:'"
if ($driveI -eq $null) {
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 ($testdrv -eq $null)
{
$s = $s.Trim([char]0x0027)
Set-WmiInstance -input $driveI -Arguments @{DriveLetter=$s}
Write-Host I: has been moved to $s
break
}
}
}