如何在 PowerShell 中将整数变量转换为字符串变量?
powershellmicrosoft technologiessoftware & coding更新于 2026/2/14 22:07:17
要将整数变量转换为字符串变量,您需要使用显式转换或函数方法。在下面的例子中,我们将一个整数值赋给变量 $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

