PowerShell で文字列を整数に変換する

このチュートリアルでは、PowerShell で文字列を整数に変換する方法を説明します。
PowerShell で [int]
を使用して文字列を整数に変換する
以下に示すように、変数 $a
があると考えてみましょう。
$a = 123
$a
のデータ型は整数です。
$a.GetType().Name
出力:
Int32
ただし、値を" "
で囲むと、データ型は string
になります。
$b = "123"
$b.GetType().Name
出力:
String
このような文字列データ型を整数に変換するには、以下に示すように [int]
を使用できます。
$b = $b -as [int]
$b.GetType().Name
出力:
Int32
PowerShell で文字列を整数に変換する変数のデータ型を定義する
PowerShell は、変数のデータ型を独自に検出できます。
データ型を特定して変数を宣言する必要はありません。ただし、変数のデータ型をその前に定義して、データ型を強制できるようにすることができます。
例えば:
[int]$c = "456"
$c.GetType().Name
出力:
Int32
整数データ型を文字列値に強制しようとすると、エラーが発生します。
[int]$data = "storage"
出力:
Cannot convert value "storage" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ [int]$data = "storage"
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
著者: Rohan Timalsina