在 Powershell 中,将字符串转换为 int 的惯用方法是什么? [英] In Powershell what is the idiomatic way of converting a string to an int?

查看:31
本文介绍了在 Powershell 中,将字符串转换为 int 的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的唯一方法是直接转换:

The only method I have found is a direct cast:

> $numberAsString = "10"
> [int]$numberAsString
10

这是 Powershell 中的标准方法吗?是否预计之前会进行测试以确保转换成功,如果成功,如何进行?

Is this the standard approach in Powershell? Is it expected that a test will be done before to ensure that the conversion will succeed and if so how?

推荐答案

使用 .net

[int]$b = $null #used after as refence
$b
0
[int32]::TryParse($a , [ref]$b ) # test if is possible to cast and put parsed value in reference variable
True
$b
10
$b.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

注意这一点(powershell 强制功能)

note this (powershell coercing feature)

$a = "10"
$a + 1 #second value is evaluated as [string]
101 

11 + $a # second value is evaluated as [int]
21

这篇关于在 Powershell 中,将字符串转换为 int 的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆