PowerShell, just as it is the case with numerous languages, makes extensive use of objects. PowerShell Data types are used to “categorize” various kinds of objects using distinct schemas of properties and functions.
Once you understand PowerShell data types, you’ll appreciate the efficiency of a concept known as PowerShell type accelerators. Accelerators are PowerShell techniques for allocating data types faster.
In this tutorial, I will be helping you learn about different object data types as well as how to utilize accelerators to make working with them simpler.
Example of Type Accelerators
For users who have never heard of accelerators, chances are they have used them some time while coding. When getting types using PowerShell, you’ll see that [Bool], [Array], and [String] are type accelerators. These class accelerators allow you to quickly access longer.NET definitions.
- [CmdletBinding] → [System.Management.Automation.CmdletBindingAttribute]
- [Array] → [System.Array]
What are our choices for utilizing accelerators in PowerShell, and how can we find out what they are?
Keep reading as I take you through a journey of the different type accelerators!
Get Type Accelerators to learn about PowerShell Data Types
PowerShell has a one-line command that returns all of the accelerators that PowerShell has. For instance, in a PowerShell 7 context, the possible type accelerators are shown below.
Here is the one-line command:
[PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Get
Key Value --- ----- Alias System.Management.Automation.AliasAttribute AllowEmptyCollection System.Management.Automation.AllowEmptyCollectionAttribute AllowEmptyString System.Management.Automation.AllowEmptyStringAttribute AllowNull System.Management.Automation.AllowNullAttribute ArgumentCompleter System.Management.Automation.ArgumentCompleterAttribute array System.Array bool System.Boolean byte System.Byte char System.Char CmdletBinding System.Management.Automation.CmdletBindingAttribute
It’s a distinct job to figure out how to utilize each accelerator. To do this, it is important to understand how an accelerator’s constructors work. We may get the required arguments for a constructor by using the GetConstructors function.
We begin by retrieving the URI accelerator, which reveals that there are six distinct kinds. Reading the Microsoft reference materials frequently clarifies how to use the class if the result isn’t always obvious about the value to use.
Here is a script to retrieve URI accelerator in Powershell:
( [Type]"URI" ).GetConstructors() | ForEach-Object { ( $_.GetParameters() | ForEach-Object { $_.ToString() } ) -Join ", " }
The result should look like this:
System.String uriString System.String uriString, Boolean dontEscape System.Uri baseUri, System.String relativeUri, Boolean dontEscape System.String uriString, System.UriKind uriKind System.Uri baseUri, System.String relativeUri System.Uri baseUri, System.Uri relativeUri
All You Need to Know About Accelerators For PowerShell Data Types
Let’s get started utilizing the most popular PowerShell data types accelerators now that we know where to look for them and what constructors they utilize.
Uniform Resource Identifiers (URI)
The manipulation of URIs (Uniform Resource Identifiers) and URLs (Uniform Resource Locators) may be tricky. Using string manipulation to retrieve the values you need is often the only option. For these situations, .NET provides the URI type accelerator.
The example below shows how to use the Uniform Resource Identifier accelerator with a basic Uniform Resource Locator. The output is the URI’s component segments, which allows for considerably faster manipulation.
[URI]"https://facebook.com"
The outcome (The URI type’s schema) should look like this:
There are easy methods available for additional usage after you have a URI object, as seen in the Get-Member result shown below.
$URI = [URI]"https://facebook.com" $URI | Get-Member -Type Method
The outcome should look like this:
TypeName: System.Uri Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object comparand) GetComponents Method string GetComponents(System.UriComponents components, System.UriFormat format) GetHashCode Method int GetHashCode() GetLeftPart Method string GetLeftPart(System.UriPartial part) GetObjectData Method void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInf... GetType Method type GetType() IsBaseOf Method bool IsBaseOf(uri uri) IsWellFormedOriginalString Method bool IsWellFormedOriginalString() MakeRelative Method string MakeRelative(uri toUri) MakeRelativeUri Method uri MakeRelativeUri(uri uri) ToString Method string ToString()
WMI, WMIClass, WMISearcher
WMI, or Windows Management Instrumentation (WMI), is a term that many long-time PowerShell admins are familiar with. The WMI framework contains a lot of Windows settings.
So, what can the Windows Management Instrumentation, Windows Management Instrumentation Searcher, and Windows Management Instrumentation Class accelerators accomplish for us?
- WMIClass — Get access to a class’s static properties and methods.
- WMISearcher — Perform a WMI object search.
- WMI — Retrieve a class’ single instance.
The script below shows you how to make the notepad.exe process, find it, and then get further information about it using all three ways.
# This step Creates the notepad.exe Process $ProcessManager = [WMICLASS]"root\cimv2:WIn32_Process" $ProcessManager.Create("notepad.exe") # This step is used to find the notepad.exe process $Search = [WmiSearcher]'SELECT * FROM Win32_Process' $Processes = $Search.Get() $Process = $Processes | Where-Object Name -Match "Notepad" # Here I would retrieve the notepad.exe process using WMI accelerator $WMIProcess = [WMI]("\.\root\cimv2:Win32_Process.Handle='{0}'" -F $Process.ProcessId)
XML
It’s difficult to work with XML documents. XML is a versatile, yet complex, format. In any language, parsing through a lengthy and complicated text is tough.
Using the PowerShell data type accelerator XML, PowerShell makes this much simpler. Get-Content allows you to take an XML document from a string or a file.
$XML = [XML]"<reminder> <to>Afam</to> <from>Zikora</from> <heading>Alarm</heading> <body>Remember it's Afam's birthday this weekend!</body> </reminder>"
It’s clear that navigating the nodes to locate a particular value is simple. Let’s suppose we do not need the header child node.
With the SelectNodes method, you can quickly execute XPath searches. Remove a node using the RemoveChild method after using SelectSingleNode to target a single node.
DateTime
Working with dates in scripts is a common need in PowerShell. Date and time may be manipulated in a variety of ways. Using the PowerShell data type [DateTime] accelerator is a simple approach with many helpful features. The following are some of the most helpful techniques:
- Date Time Arithmetic Operations
- Formatting a Date Time
- Parsing a Date Time String
How to Use Date Time Arithmetic Operations
It’s critical to be able to add and remove time from an existing DateTime object. Use the DateTime class to execute these actions instead of complex workarounds.
([DateTime]::Parse('2021-08-10')).AddDays(4) (([DateTime]::Parse('2021-08-10')).AddDays4)).AddMonths(-3)
How to Format a Date Time
A date-time string in a certain format is often required in data files. For instance, let’s use the ToString function to convert the date we just generated. We’ll provide the custom date format MM dd yyyy-hh:mm:ss to this function. Although this is not a common format, we may print the date in this format using the ToString function.
([DateTime]::Parse('2021-08-10')).ToString('MM_dd_yyyy-hh:mm:ss')
How to Parse a Date Time String
The DateTime accelerator will produce a genuine System.DateTime object when given a recognized date format (i.e., not a bespoke format), which is the same object type as the Get-Date method.
[DateTime]::Parse('2020-08-10')
RegEX
Complex searches inside text material are made simpler using (RegEx) Regular Expressions. Constructing these questions in and of themselves is a problem. After you’ve perfected your query, you may utilize the PowerShell RegEx accelerator to quickly match text information.
Despite the fact that the regex type accelerator is not strictly a PowerShell data type, it may significantly reduce the time it takes to execute regex matches.
A basic RegEx matching technique is shown below. To conduct a search, create a basic regular expression and use the Match function on a text string.
([RegEx]'\d{5}').Match('This script finds the first 5 elements, like 12345').Value
TimeSpan
The TimeSpan class, just like the DateTime class, makes dealing with time ranges simple. Extra mathematical operations, including multiplication and division, are accessible, unlike DateTime.
How to Make a TimeSpan Object
A timespan value may be constructed in a variety of ways. The Hours/Minutes/Seconds constructor is used in my example. Other constructors that might be used are listed below.
Ticks
Hours/Minutes/ Seconds
Days/Hours/Minutes/Seconds
Days/Hours/Minutes/Seconds/Milliseconds
$TimeSpan = [TimeSpan]::New(1,0,0) $TimeSpan
How to Multiply and Divide on TimeStamp
Let’s suppose you’ve established a time range, but you’d want to know what three times that range is. Using the Multiply technique makes it easy.
$TimeSpan.Multiply(4)
You can perform other functions by substituting “Multiply” for Divide for example.
PSCredential
When dealing with online services, distant systems, or third-party apps, securing credentials is essential. PSCredential is a class that encrypts a password and saves it as an object. Authentication is made simple by passing this object to functions and cmdlets.
In the example below, we’ll create a PSCredential object to hold our secure values. It’s worth noting that the password value must be a safe string.
🎏FAQ
How to check data types in PowerShell?
To determine the data type of a value in PowerShell, use the “Get-Type” cmdlet. This cmdlet returns a “Type” object that symbolizes the value’s data type.
You can use the following command, for instance, to determine the data type of a string value:-
Get-Type “hello”
This will return a “Type” object with the name “String”.
The “Get-Type” cmdlet can also determine a variable’s data type by providing the variable name as the input.
$x = “hello”
Get-Type $x
This will also return a “Type” object with the name “String”.
The “Get-Type” cmdlet also allows you to specify an expression as input to determine the data type of that expression.
For example:-
Get-Type (1 + 2)
This will return a “Type” object with the name “Int32”.
To obtain the complete name of the data type, utilize the “FullName” attribute of the “Type” object.
For example:-
$type = Get-Type “hello”
$type.FullName
This will return “System.String”.
To determine whether a data type is a primitive type, you may also use the “IsPrimitive” attribute (such as a string, integer, or boolean).
$type = Get-Type “hello”
$type.IsPrimitive
This will return “True”.
How do I declare a datatype in PowerShell?
To create an instance of a.NET object, including instances of data types, with PowerShell, use the “New-Object” cmdlet.
You can use the following command, for instance, to create an instance of the “System.Int32” data type:
$x = New-Object System.Int32
By doing this, a variable named “$x” that is an instance of the “System.Int32” data type will be created. The assignment operator (=) can then be used to give the variable a value.
For example:-
$x = New-Object System.Int32
$x = 10
This will assign the value 10 to the variable “$x”.
Another option is to create an instance of a data type and then give it a value all at once using the “New-Object” cmdlet.
For example:-
$x = New-Object System.Int32 10
This will produce the “System.Int32” data type instance “$x” and give it the value 10 as a variable name.
The “Get-Type” cmdlet can be used to check a variable’s data type.
For example:
$x = New-Object System.Int32 10
Get-Type $x
This will return a “Type” object with the name “Int32”.
Note:– Data types are shown in PowerShell as .NET objects. For instance, the 32-bit integer data type is represented by the.NET object “System.Int32”.
What are the most common data types used in PowerShell?
The most popular data types in PowerShell include:-
String:- Characters are arranged in a string. The “System.String” data type in .NET represents it. A string can be enclosed in single or double quotations.
For example:-
$x = “hello”
$y = ‘world’
Integer:- Whole numbers are known as integers. In the.NET platform, it is represented by the “System.Int32” data type. A 64-bit integer can be specified by adding the suffix “L”.
For example:-
$x = 10
$y = 10L
Float:- A decimal number is referred to as a float. In .NET, it is depicted by the “System.Double” data type. A single-precision float can be specified by adding the suffix “f”.
For example:-
$x = 10.5
$y = 10.5f
Boolean:- Boolean values can either be “True” or “False.” In.NET, it is depicted by the “System.Boolean” data type.
For example:-
$x = $True
$y = $False
Array:- A set of values is referred to as an array. In .NET, the “System.Array” data type serves as its representation. The “,” operator can specify an array of values.
For example:
$x = 1,2,3
$y = “a”,”b”,”c”
Many additional sorts of data can be used in PowerShell, but these are some of the most typical ones.
To create instances of these data types, you can use the “New-Object” cmdlet and the “Get-Type” cmdlet to check the data type of a value.
Final Thoughts on PowerShell Data Types
PowerShell Data Types accelerators make complicated PowerShell tasks simple. There are numerous kinds of accelerators, but using these techniques, you should be able to utilize Powershell to find new ones.
Accelerators may be used in a variety of ways. Understanding these distinctions can significantly boost your productivity!