当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 将字符串转换为整数

作者:精品下载站 日期:2024-12-14 17:00:50 浏览:15 分类:玩电脑

PowerShell 将字符串转换为整数


在 PowerShell 中,当需要对存储为字符串的值执行数学或条件运算时,需要将字符串转换为整数。

使用 PowerShell 中的 int 转换运算符或 TryParse() 方法在 PowerShell 中将字符串转换为 int。

在本文中,我们将讨论如何使用 PowerShell 脚本将 string 转换为 int。

使用 int Casting Operator 在 PowerShell 中将 String 转换为 Int

在PowerShell中使用int转换运算符将字符串转换为整数,它会尝试解析字符串并获取整数值。

# Declare string variable
$str = "100"

# Get the data type of the variable
$str.GetType()

# converting string to int
$num1 = [int]$str

# Print the number
$num1

# Get the data type of the variable
$num1.GetType()

在上面的 PowerShell 脚本中,$str 变量是包含值 "100" 的字符串类型。使用[int]转换运算符,它将字符串转换为整数,并将结果分配给包含值100的$num1变量。

PowerShell 中的 GetType() 方法获取变量的数据类型。

使用 int 转换运算符将字符串转换为 int 的上述 PowerShell 脚本的输出是:

[玩转系统] PowerShell 将字符串转换为整数

酷提示:如何在 PowerShell 中将整数转换为字符串!

在PowerShell中使用TryParse方法将字符串转换为Int

使用 System.Int32 类中的 TryParse() 方法在 PowerShell 中将字符串转换为整数。该方法有两个参数:一个要转换的字符串和一个用于存储转换后的值的变量。

如果解析成功,TryParse 方法将返回值 True 并将结果存储在变量中。如果解析不成功,则返回False

$str = "100"
# Declare variable
$num2 = 0
# Use TryParse method to convert string to int
$result = [System.Int32]::TryParse($str,[ref]$num2)
$num2

在上面的 PowerShell 脚本中,$str 变量是包含值 "100" 的字符串类型。 $num2 变量声明为值 0,用于 TryParse 方法。

System.Int32 类中的 TryParse() 方法采用 $str$num2 参数并解析它们。

上述用于将字符串转换为整数的 PowerShell 脚本的输出是:

PS D:\> $str = "100"                                                                               
PS D:\> $num2 = 0                                                                                 
 PS D:\> $result = [System.Int32]::TryParse($str,[ref]$num2)                                        PS D:\> $num2                                                                                      
100

结论

希望上面关于如何在 PowerShell 中使用 int 转换运算符和 TryParse 方法将 string 转换为 int 的文章对您有所帮助。

在 PowerShell 中,它具有 Parse() 方法,该方法也可以将字符串转换为 int,但如果 PowerShell 字符串不是有效的整数,则此方法可能会引发异常。因此,要处理异常,请使用 TryParse() 方法。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯