brad p
brad p

Reputation: 97

How do you convert data types in Windows Powershell?

I'm very new to powershell and am running into walls trying to convert a string to a integer.

If I run the following command: Get-DefaultAudioDeviceVolume it often returns a number that looks something like: 50.05816%, which I have confirmed to be a string. I need to convert this to a whole number integer (50). Obviously I could hard code the integer in my script, but for the purpose of the script I need it to be flexible in it's conversion. The result of the previous test changes and I want to pass along the whole integer further down the line.

Thanks in advance!

Upvotes: 5

Views: 19589

Answers (2)

henrycarteruk
henrycarteruk

Reputation: 13227

If the string contains the % symbol you would need to remove this, then you can use the -as operator to convert to [int]

[string]$vol = "50.05816%"

$vol_int = $vol.Replace('%','') -as [int]

The -as operator is very useful and has many other uses, this article goes through a number of them: https://mcpmag.com/articles/2013/08/13/utilizing-the-as-operator.aspx

Upvotes: 3

whatever
whatever

Reputation: 891

Just cast it to integer and replace the "%" with nothing:

[int]$var = (Get-DefaultAudioDeviceVolume).Replace("%","")

Powershell does automatic type casting and starts from the left. So when $var is defined as an integer, it will try to convert the right side to the same type.

Upvotes: 2

Related Questions