2016-08-30 58 views
0

我試圖創建一個函數,要求用戶輸入驅動器的大小,如果驅動器大小大於100,則要求用戶再次輸入它。我的腳本只是口口聲聲說「無法要求更多,然後100GB」,即使用戶輸入50大於問題

這裏是我的腳本

param (
     [string]$MaxC = "100" 
) 

function cDrive { 

    $C_DiskGB = Read-Host "C: Drive - Disk Size in GB" 
     if ($C_DiskGB -gt $MaxC) { 

       Write-Host "Cannot ask for more then 100gb of disk space. Please re-enter how much disk space you need for the c: drive" 
       cDrive 

      } 
     else { 

      Write-Host "C: Drive is $C_DiskGB GB" 

      } 

} 

,當我把東西少的輸出是: C:驅動器 - 磁盤GB大小:50 不能要求超過100GB的磁盤空間。請重新輸入c:驅動器需要多少磁盤空間。C:驅動器 - 磁盤大小(GB):

任何幫助都非常感謝。謝謝!

+3

我認爲問題是,你要比較一個字符串一個整數,嘗試:如果([INT] $ C_DiskGB -gt $ MAXC) –

回答

1

好的,讓我們從比較字符串開始,當你想比較數字。將變量定義爲數字([int]),問題應該自行解決。

其次,你打破範圍。不可怕,但不容易推薦。下面是我建議:

function cDrive { 
Param([int]$MaxC = 100) 
    [int]$C_DiskGB = Read-Host "C: Drive - Disk Size in GB" 
    While($C_DiskGB -gt $MaxC){ 
     [int]$C_DiskGB = Read-Host "Cannot ask for more then $MaxC`gb of disk space. Please re-enter how much disk space you need for the c: drive" 
    } 
    Write-Host "C: Drive is $C_DiskGB GB" 
} 
+0

奏效謝謝! –