Home Tech Get Type Accelerators To Learn About PowerShell Data Types

Get Type Accelerators To Learn About PowerShell Data Types

0

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:

powershell data types

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>"

powershell data types

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.

Get Type Accelerators To Learn About PowerShell Data Types

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')

Get Type Accelerators To Learn About PowerShell Data Types

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

Get Type Accelerators To Learn About PowerShell Data Types

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.

We’ll create a PSCredential object to hold our secure values in the example below. It’s worth noting that the password value must be a safe string.

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!