2015-05-11 105 views
1

我正在嘗試編寫一個PowerShell腳本來將I的驅動器號更改爲其他內容。這是腳本。將字符串變量作爲Powershell中的參數傳遞

$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:不存在。 另一方面,如果我存在,我試圖找到一個免費的驅動器盤符。我正在使用foreach循環執行我的搜索。現在,當我們撥打Get-WmiObject時,我們使用單引號的驅動器號。但是當我們使用Set-WmiInstance時,我們使用雙引號。但是,即使我修改$s以包裝雙引號,它不起作用。 總之,如果我使用Write-Host $s,我得到輸出,比如"E:"。當我使用Set-WmiInstance -input $driveI -Arguments @{DriveLetter="E:"}時,它工作。但是當我使用Set-WmiInstance -input $driveI -Arguments @{DriveLetter=$s}時,它不起作用。誰能告訴我我做錯了什麼?

+1

在您的工作示例中,您傳遞的是一個字符串,該字符串被引用爲您如何定義文字字符串。在非工作示例中,您傳遞的是一個字符串,在其中您使用引號進行編碼。我不知道這是否是問題,因爲沒有驅動器叫做「E:」,但實際上只是'E:'。如果將行更改爲'$ s = $ s.Trim([char] 0x0027)'會發生什麼? – Matt

+1

將驅動器字母定義爲簡單的字符串...'@s in @(「Z:」,「Y:」,....'然後您的過濾器將如下所示:'-Filter「DriveLetter ='$ s' 「'你可以擺脫整個$ s ='''+ $ s.Trim([char] 0x0027)''''''亂七八糟。 –

回答

2

不管怎樣,以後要刪除它們時不要將引號放在字符串中。相反,加,你真正需要他們的報價:

$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 
    } 
} 
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 
     } 
    } 
} 
相關問題