How to check data types in PowerShell scripts

How to check data types in PowerShell scripts

PowerShell script to check data types.

Variables are marked with $. It is like $a.

Type $a.GetType().FullName and it will show you the one.

Here is an example.

PS C:\work_ps> $a=1;$a.GetType().FullName;
System.Int32
PS C:\work_ps>

In PowerShell, numbers seem to be of type System.Int32.

Next, let’s examine strings.

PS C:\work_ps> $a='abc';$a.GetType().FullName;
System.String
PS C:\work_ps>

The string type appears to be System.String.

Try concatenating a number and a string with +.

PS C:\work_ps> $a='abc';$b=1;($a+$b)
abc1
PS C:\work_ps> $a='abc';$b=1;($a+$b).GetType().FullName;
System.String
PS C:\work_ps>

String type.

If you want to explicitly convert a variable to a String type, prefix the variable name with [String].

Here is an example

PS C:\work_ps> $a=1; $a = [String]$a; $a.GetType().FullName;
System.String
PS C:\work_ps>

You will see that the type is changed to System.String type.

Conversely, if you want to convert it to System.Int32 type, prefix the variable name with [int].

PS C:\work_ps> $a='1';$a = [int]$a;$a.GetType().FullName;
System.Int32
PS C:\work_ps>

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL