如何在PowerShell中將整型變數轉換為字串變數?
要將整型變數轉換為字串變數,需要使用顯式轉換或函式方法。在下面的示例中,我們將一個整數值賦值給變數$X。
$x = 120 $x.GetType().Name
現在,當您檢查該變數的資料型別時,它將是**Int32**。
要將其轉換為字串變數,首先我們將使用顯式方法,使用方括號和要轉換的資料型別。
[string]$x = 130 $x.GetType().Name
$x 的資料型別是**String**。
在第二種方法中,您可以使用PowerShell函式方法ToString()進行轉換。**例如**,
$x = $x.ToString() $x.GetType().Name
同樣,您可以將字串值轉換為整數值,但要在其定義的範圍內。**例如**,
$x = "123" [int]$x = $x $x.GetType().Name
在這裡,我們宣告“**123**”為字串變數,為了轉換它,我們將在$x之前使用[int]資料型別,因此它將被轉換為整型變數。但是,當您將字元字串轉換為整數時,將會出現錯誤。
例如,
$x = "abc" [int]$x = $x
Cannot convert value "abc" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:1 + [int]$x = $x + ~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId :RuntimeException
廣告