2017-10-18 61 views
0

我嘗試添加百分號(「%」)追加到一個變量結束:PowerShell的:附加一個百分號可變

$disk = Get-WmiObject -ComputerName $Computer -Class Win32_LogicalDisk -Filter "Caption = 'D:'"  
If (!($disk)) { 
    $DiskpercentFree = "n/a" 
} 
Else { 
    $deviceID = $disk.DeviceID 
    [float]$size = $disk.Size; 
    [float]$freespace = $disk.FreeSpace; 
    $diskpercentFree1 = [Math]::Round(($freespace/$size) * 100) 
    $Percent = "%" 
    $diskpercentFree = $diskpercentFree1 + $Percent 
} 

但我得到的是:

Cannot convert value "%" to type "System.Double". Error: "Input string was not in a correct format."

推測是因爲它認爲「+」運算符正在計算?我已經嘗試了各種連續選項,但似乎無法做到正確。誰能幫忙?

回答

0

說明:

添加在你的輸出" "把它作爲一個字符串,然後將變量追加到結束。這意味着您可以將其從%切換到字符串,如Percent Remaining

希望這會有所幫助,你近了!

代碼:中$diskpercentFree

$disk = Get-WmiObject -ComputerName $Computer -Class Win32_LogicalDisk -Filter "Caption = 'D:'"  
       If (!($disk)) { 
       $DiskpercentFree = "n/a" 
       } 
       Else { 
       $deviceID = $disk.DeviceID 
       [float]$size = $disk.Size; 
       [float]$freespace = $disk.FreeSpace; 
       $diskpercentFree1 = [Math]::Round(($freespace/$size) * 100) 
       $Percent = '%' 
       $diskpercentFree = "$diskpercentFree1" + $Percent 
       } 

結果舉例:

PS C:\Windows\system32> $DiskpercentFree

57%

+1

我選擇了$ diskpercentFree = [String] $ diskpercentFree1 +「$ Percent」。我確實嘗試轉換變量:「[String] $ diskpercentFree」。非常感謝! – JDGEEK

+0

@JDGEEK然後在技術上你應該接受其他答案,因爲那是列出該方法的那個 – arco444

1

有幾個方法可以做到這一點:

分配變量作爲字符串:

$diskpercentFree = "$diskpercentFree1$Percent" 

演員的雙重價值作爲一個字符串:

$diskpercentFree = "$diskpercentFree1" + $Percent 
# Or 
$diskpercentFree = [string]$diskpercentFree1 + $Percent 

而且無需使用單獨變量爲%字符:

$diskpercentFree = "$diskpercentFree1%" 
0

我會建議字符串格式化如果你想輸出值的百分比。例子:

PS C:\> "{0:P}" -f 1 
100.00 % 
PS C:\> "{0:P1}" -f .986 
98.6 % 
PS C:\> "{0:P0}" -f .75 
75 % 

-f的文檔是在about_Operators page和有鏈接存在於.NET文檔如何實現不同的結果。