Understanding Converting Object Types with PowerShell Casting

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

The Instantiate() method of the Converter object allows PowerShell to convert one type into another. This article shows how you can use this knowledge in your scripts and applications, either for data interchange or as a performance optimization technique.

PowerShell casting is a way to convert between object types. The “powershell cast object to string” command can be used to convert an object type into its string representation.

Understanding Converting Object Types with PowerShell Casting

Because PowerShell isn’t a strict-typed language, you don’t have to declare particular kinds of objects every time you need to create one. PowerShell can convert strings to ints, dates to strings, and any other equivalent type. You may change the type of an object by casting it.

In PowerShell, everything is an object. You don’t have to tell PowerShell what sort of object you want, however.

For example, use the Get-Service command to query a service and then use the Get-Member command to discover what sort of object it returns. It’s worth noting that Get-Member returns a TypeName of type System. ServiceProcess.ServiceController.

How to Manage Services with PowerShell is a related article.

PS> Get-Service -Name wuauserv | Get-Member TypeName: System.ServiceProcess.ServiceController Name MemberType Definition —- ———- ———- <SNIP>

You didn’t have to tell PowerShell you wanted that sort of object; it merely created one for you.

But what if you don’t desire that kind of item? Perhaps you need to invoke a certain method on a specific sort of object, or you need to refer to the attributes of another object. In such situation, you’ll use PowerShell to change the type of the object or cast it to another.

Changing a String to an Integer

Casting is a programming phrase that refers to the process of “converting” one kind of object to another. However, not all things can be thrown to one another.

Assume you have a string that is defined as a number. Strings are defined by enclosing them in single or double quotations, as seen below.

PS> $string = ‘1’ PS> $string.GetType().Name String

When you look at $string’s value, you’ll see that it’s 1. It’s that simple.

Shouldn’t you be allowed to add a number to $string if it’s the number one? Let’s have a look.

Last last I looked, 1 Plus 2 didn’t equal 12. What exactly is going on?

PowerShell didn’t add the two numbers together since $string is simply string data. Instead, it concatenated the two together, thereby combining them.

To get PowerShell to add the two numbers, we must first convert $string to an int and then inform PowerShell that $string is a number. To do so, we utilize the cast operator in PowerShell to explicitly convert the text to an integer type.

PS> $string = [int]$string 1

Let’s try adding the two numbers together once again.

PowerShell now has the ability to add them together since we cast $string to an integer or utilize PowerShell to “convert” the string to an int. Casting objects completely alters their attributes, enabling you to conduct a variety of operations on them.

Other Casting Scenarios to Consider

You can cast any kind of object in PowerShell.

XML conversion

Take, for example, an XML file. An XML file is nothing more than a collection of strings. PowerShell is completely unaware that XML is a structured format.

For instance, suppose we have a basic XML file that looks like this:

<person> <firstname>Adam</firstname> <lastname>Bertram</lastname> <levelofawesome>Really high</levelofawesome> </person>

If this was in a file named C:person.xml, you’d use the Get-Content command to read it and get the XML, or what PowerShell believes are a bunch of strings.

PS C:> Get-Content C:person.xml <person> <firstname>Adam</firstname> <lastname>Bertram</lastname> <levelofawesome>Really high</levelofawesome> </person>

However, you recognize that this is XML rather than a collection of strings, and you’ll need to do some XML searches using XPath. Type accelerators are a notion in PowerShell that enables you to quickly turn a bunch of strings that look like XML into a real XML object.

PowerShell will convert the set of strings it gets from Get-Content to an XML object if you prefix the variable definition with [xml]. You can now see your reference properties, such as person, as well as all of the characteristics, listed below.

PS> [xml]$person = Get-Content -Path ‘C:person.xml’ PS> [xml]$person person —— person PS> ([xml]$person).person firstname lastname levelofawesome ——— ——– ————– Adam Bertram Really high

You can also see that the object is of type System.Xml.XmlDocument, which gives you access to a number of XML-specific methods and attributes.

Cast to XML using PowerShellCast to XML using PowerShell

How to Convert a String to a Date

We can cast strings to datetime objects or use PowerShell to transform a string to a date in a similar way to XML. Simply describe a string that looks like a date, such as 1/20/80, to construct a datetime object. This is a date to you and me, but as you can see, PowerShell has no notion. There are no date-specific activities on this page. It’s simply a piece of thread.

PS> $date = ‘1/20/80’ PS> $date | Get-Member PS C:> $date | Get-Member TypeName: System.String Name MemberType Definition —- ———- ———- Clone Method System.Object Clone(), System.Object ICloneable.Clone() CompareTo Method int CompareTo(System.Object value), int CompareTo(string strB), int IComparable.CompareTo(System.Object obj), int … Contains Method bool Contains(string value) CopyTo Method void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) EndsWith Method <SNIP>

However, prefixing that string with [datetime] converts it to a datetime object, allowing you to use a variety of datetime-specific methods and properties.

PS> [datetime]$date = ‘1/20/80’ PS> $date | Get-Member TypeName: System.DateTime Name MemberType Definition —- ———- ———- Add Method datetime Add(timespan value) AddDays Method datetime AddDays(double value) AddHours Method datetime AddHours(double value) AddMilliseconds Method datetime AddMilliseconds(double value) AddMinutes Method datetime AddMinutes(double value) AddMonths Method datetime AddMonths(int months) <SNIP>

Creating PSCustomObjects from Hashtables

Casting a hashtable to a PSCustomObject type is the final and most popular example.

PS> $person = @{‘FirstName’ = ‘Adam’; ‘LastName’ = ‘Bertram’} PS> $person.GetType().Name HashTable PS> ([pscustomobject]$person).GetType().Name PSCustomObject

You may then refer to object attributes like $person once the object is of PSCustomObject type. $person, $person, $person, $person, $person, $person, $ LastName, LastName, LastName, LastName, LastName, LastName, Last

Summary

You learnt how PowerShell handles objects and how PowerShell casts some objects to others in this blog article. We went through some basic casting, such as strings to integers and strings to datetime objects, as well as a PowerShell concept called type accelerators, which allows you to cast items to a variety of.NET types quickly.

Check out Building Custom Object Kinds with PowerShell and PSTypeName to learn more about how PowerShell handles objects and even how to create your own custom types using the lesser-known PSTypeName capability.

The “powershell toint32” is a PowerShell cmdlet that converts an integer, string, or date/time into 32-bit signed integers. This can be done by using the ToInt32() method on any of these types.

Frequently Asked Questions

What is type casting in PowerShell?

How do you change a datatype in PowerShell?

A: To change a datatype in PowerShell, use the Set-Variable cmdlet with the type name and value. For example, to set a string variable called mystring to uppercase letters, you would enter Set -variable mystring -type String -value MYSTRING

How do I convert an object to a string in PowerShell?

A: * [System.String]::Format(This is %s, My string)

Related Tags

  • powershell casting to string
  • powershell cast string to int
  • powershell convert string to object array
  • powershell data types
  • powershell data type conversion

Table of Content