PowerShell’s Docs General Docs Useful .NET classes for PowerShell

Microsoft's .NET framework provides a class library you can use in your PowerShell scripts. This wiki doc lists the most useful classes for system administration. For each class we provide an example that shows how you can use the class. If you know of other useful classes, please just edit the doc.

Introduction to classes and objects ^

A class is a code template that defines properties and methods (functions). To use the class, you have to instantiate (create) an object. For instance, windows in a graphical user interface have properties such as the window title, the size of the window, or the position on the screen. The window class contains all property windows the user interface can have.

The methods of the class determine what you can do with the window. For example, you can move the window to a different screen position, minimize it, or change its size. Once you create a concrete window in your program, you have instantiated an object of the window class.

A hierarchical namespace organizes classes. This allows you to locate a class in the .NET framework through a fully qualified name. For instance, the fully qualified name of the window class is System.Windows.Window.

Here is another example of the math class:

[System.Math]: This class contains functions and properties for mathematical operations. System.Math is the full path of the namespace.
[System.Math]::Pi: PI is a property and returns the value of Pi (3.14…).
[System.Math]::Pow($x,$y): Pow is a method (to the power of) that returns the value of x to the power of y.

Methods always end with parentheses (), which you can use to pass in values to the method.

The classes below list their names in the namespace and give usage examples in certain scenarios.

Subscribe to 4sysops newsletter!

IO.FileStream ^

  • NameSpace: IO.FileStream
  • Example: Create—create a file with a specific size
  • Scenario: Filling up a disk to see if the thresholds in your monitoring systems work correctly
  • Code:
#1:
$my10MBFile = New-Object System.IO.FileStream 'C:\Temp\my10MBFile.abc', Create, ReadWrite
#2:
$my10MBFile.SetLength(10MB)
#3:
$my10MBFile.Close()
<#

to 1.
Create a new object based on the FileStream class located in the System.IO namespace and store the object in the variable $my10MBFile.  'Create' sets the I/O mode and 'ReadWrite' sets the file-access mode; in this case it's ReadWrite.

to 2.
Calls the SetLength function on the object now stored in $my10MBFile, passing in the size

to 3.
Calls the Close function to write to the disk and release the handle
#>

Net.Dns ^

  • NameSpace: Net.Dns
  • Example: Resolve—get the IP address from a DNS name
  • Scenario: Using nslookup functionality in PowerShell
  • Code:
$remoteName = 'mailServerName'

$remoteIP = [System.Net.DNS]::Resolve($remoteName).AddressList | Where-Object { $_.AddressFamily -eq 'interNetwork' } | Select-Object -ExpandProperty IPAddressToString

<#
Calls the function ‘Resolve’ based on the class DNS, which is part of the System.Net namespace. This should pass the resolved name as a parameter to the ‘Resolve’ function.

The function returns an object of the type ‘IPHostEntry’. The remaining lines with Where-Object and Select-Object are required only to retrieve the IP address. It finally stores the IP address in $remoteIP.
#>

Double ^

  • NameSpace: Double
  • Example: Parse—convert a string to a double (64-bit floating-point value)
  • Scenario: Importing numbers from a text file where double quotes encapsulate every number
  • Code:
$numberAsAString = "1.23456789"
$numberAsNumber = [double]::Parse($numberAsAString)

<#
Calls the function ‘Parse’ based on the class double, which is part of the System namespace. This passes the string to convert to a number as a parameter to the ‘Parse’ function.

Note: [double] is a so-called ‘type accelerator’ and actually stands for [System.Double]. PowerShell provides several accelerators that allow you to access .NET more easily.
#>

DateTime ^

  • NameSpace: DateTime
  • Example: ParseExact—convert a string to a DateTime
  • Scenario: A need to process a date from a German application with your script
  • Code:
$germanDate = '23.12.2017'
$valideDate = [DateTime]::ParseExact($germanDate,'dd.MM.yyyy',[Globalization.CultureInfo]::InvariantCulture)

<#
Calls the function ‘ParseExact’ based on the class DateTime, which is part of the System namespace. This passes the string (to convert to a date) to the ‘ParseExact’ function as the first parameter. The second parameter is the date-format. The date format is dd(day, day), period MM (month, month) period yyyy (year, year, year, year). The third and last parameter passed to the function ‘ParseExact’ is the property InvariantCulture out of the class CultureInfo located in the namespace System.Globalization. It ensures the user's culture settings can't and won't change the date format.
#>

DateTime ^

  • NameSpace: DateTime
  • Example: UtcNow—retrieve the local time as a universal time clock (UTC) value
  • Scenario: UTC is a time format that makes time relative. You do not need to consider different time zones when working with it.
  • Code:
$time = [DateTime]::UtcNow.ToString()

<#
Retrieves the property ‘UtcNow’ from the System.DateTime namespace. The ‘ToString()’ function changes the returned DateTime object to a string that it then stores in $time.
#>

TimeZoneInfo ^

  • NameSpace: TimeZoneInfo
  • Example: Local—display the current time zone
  • Scenario: Collecting information from machines located in different countries
  • Code:
currentTimeZone = ([TimeZoneInfo]::Local).DisplayName

<#
Retrieves information from the property ‘Local’ out of the class TimeZoneInfo, which is part of the System namespace. Results in an object that selects and stores the property ‘DisplayName’ in $currentTimeZone.
#>

Collections ^

  • NameSpace: Collections
  • Example: ArrayList
  • Scenario: Storing individual values in a list for further processing
  • Code:
$lazyList = New-Object System.Collections.ArrayList
$lazyList.Add("a")
$lazyList.Add("c")
$lazyList.Add("b")
$lazyList #returns a c b

$lazyList.Sort()
$lazyList #returns a b c

$lazyList.Reverse()
$lazyList #returns c b a

$lazyList.Remove("a")
$lazyList #returns c b

<#
Arrays become slow and require a lot of resources if they get too large. ArrayLists handle large amounts of data much better. Additionally, they allow you to delete individual elements.

Note: You can store elements of different types in an ArrayList. For example, $lazyList.Add(1), $lazyList.Add(“one”) works. –> ArrayLists are not type-safe!

This can lead to unexpected errors. For example, sorting can only work if the type is same (for instance, int or string).
#>

Collections.Generic ^

  • NameSpace: Collections.Generic
  • Example: List
  • Scenario: Storing individual values in a list for further processing
  • Code:
$safeList = New-Object System.Collections.Generic.List[int]
$safeList.Add(1)
$safeList.Add(3)
$safeList.Add(2)

$safeList #returns 1 3 2

$safeList.Sort()
$safeList #returns 1 2 3

<#
Generic Lists are better than ArrayLists. They are type-safe. The declaration line mentions New-Object System.Collections.Generic.List[int] as the allowed type. This example uses int (integer values).

Trying to add a float value to such a list will result in an obvious error, which one can easily find and fix.
#>

Collections.Generic ^

  • NameSpace: Collections.Generic
  • Example: Dictionary
  • Scenario: Storing key/value pairs in a list for further processing
  • Code:
$employeeDirectory = New-Object -TypeName 'System.Collections.Generic.Dictionary[int,string]'
$employeeDirectory.Add(1,'Alf, Melmug') #Adding items to the dictionary
$employeeDirectory.Add(2,'Berta, Banana')
$employeeDirectory.Add(3,'Conan, TheDetective')
$employeeDirectory #retrieving the whole dictionary

$employeeDirectory.Item(2) #Returns Berta, Banana

$employeeDirectory.ContainsValue('Alf, Melmug') #Returns $true

$employeeNumber =3
$theGuyIJustKnowTheNumber = '' #declaring an empty variable for later use

 
$employeeDirectory.TryGetValue($employeeNumber,[ref]$theGuyIJustKnowTheNumber)
$theGuyIJustKnowTheNumber #returns Conan, TheDetective

<#
Usually we use hashsets to store key value pairs in a convenient way. For example:

$mySimpleDictionary = @{1 = 'Alf'}
$mySimpleDictionary.Add(2,'Berta')
$mySimpleDictionary.Add(‘Three’,3)
…

Hashsets are not type-safe because keys and values don’t have to be of the same data type. This may lead to some unexpected results.

Generic dictionaries are type-safe. The first line initializes the dictionary. It defines that the key must be an integer and the value has to be a string. If you try to add data that does not match, an error will occur.
#>
Storing key:value pairs in a list for further processing

Storing key:value pairs in a list for further processing

Text ^

  • NameSpace: Text
  • Example: StringBuilder
  • Scenario: Constructing a string containing a lot of text, for example, adding more information in a loop each time and finally displaying or writing this string to a file
  • Code:
$veryLargeText = New-Object System.Text.StringBuilder
$veryLargeText.Append('This is')
$veryLargeText.Append('very, very ')
$veryLargeText.Append('...')
$veryLargeText.Append('long text processed by this script.')

$veryLargeText.Insert(7,' a ') #inserting text after the 7ths character
$veryLargeText.ToString() #returns This is a very, very ...long text processed by this script.

$veryLargeText.Replace('long','huge')
$veryLargeText.ToString() #returns This is a very, very ...huge text processed by this script.

<#
When constructing a string from substrings, string concatenation is the method you will use.

For example:
$allArrayInformation = ""
$myArray = @(1,4,6,8,100)

$myArray | ForEach-Object {
                    $allArrayInformation += 'This is one element:' + $_ + "`n"
}

$allArrayInformation
This is one element:1
This is one element:4
This is one element:6
This is one element:8
This is one element:100

For small strings, this approach works fine. In the background, every time you use += it creates a new string while preserving the existing content and adding the new string.

However, StringBuilder is more efficient and requires fewer resources.
#>

Management ^

  • NameSpace: Management
  • Example: PSReference
  • Scenario: Returning more value from a function
  • Code:
Function Format-Strings {

param (
              [object]$inputString,
              [ref]$outputUpper,
              [ref]$outputLower,
              [ref]$statusMessage
)

     if (($inputString.GetType()).Name -eq 'String') {
           $returnCode          = 0
           $statusMessage.Value = "OK. InputString $($inputString) is a String."
           $outputUpper.Value   = $inputString.ToUpper()
           $outputLower.Value   = $inputString.ToLower()
     } else {
         $returnCode          = 1
         $statusMessage.Value = "Not OK! InputString $($inputString) is a $($inputString.GetType())."
     }

     $returnCode

}

$textInUpperCase   = ''
$textInLowerCase   = ''
$functionStatusMsg = ''
$aText = "TestinG"

$functionReturnCode = Format-Strings -inputString $aText -outputUpper ([ref]$textInUpperCase) ‑outputLower ([ref]$textInLowerCase) -statusMessage ([ref]$functionStatusMsg)

$functionReturnCode # Returns 0
$textInUpperCase # Returns TESTING
$textInLowerCase # Returns testing
$functionStatusMsg # OK. InputString TestinG is a String.

$textInUpperCase   = ''
$textInLowerCase   = ''
$functionStatusMsg = ''

$aNumber = 132.34

$functionReturnCode = Format-Strings -inputString $aNumber -outputUpper ([ref]$textInUpperCase) ‑outputLower ([ref]$textInLowerCase) -statusMessage ([ref]$functionStatusMsg)

$functionReturnCode # Returns 1
$textInUpperCase # stays empty
$textInLowerCase # stays empty
$functionStatusMsg # Returns 'Not OK! InputString 132.34 is a double.'
<#

References give you a way to return more than one value from a function and the ability to retrieve the individual return values.
#>

DirectoryServices.ActiveDirectory.Domain ^

  • NameSpace: DirectoryServices.ActiveDirectory.Domain
  • Example: GetComputerDomain—get the computer domain name
  • Scenario: A script runs as 'System' (perhaps inside a Scheduled Task) and requires the domain information; $env:UserDNSDomain is not available in this case
  • Code:
$localComputerDomain = ([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()).Name

<#
Calls the function ‘GetComputerDomain’ of the class ActiveDirectory located in the System.DirectoryService namespace. This filters the resulting object with the property ‘Name’ and stores it in $localComputerDomain.
#>

DirectoryServices ^

  • NameSpace: DirectoryServices
  • Example: DirectorySearcher—search Active Directory without doing so from any domain-joined Windows computer and without having administrative tools installed.
  • Scenario: Retrieving all properties of the computer you're logged on to.
  • Code:
$objADSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objADSearcher.Filter = "(&(objectCategory=computer)(cn=$env:computername))"
$myComputerInAD = $objADSearcher.FindOne()
$myComputerInAD | Format-List
$myComputerInAD | Select-Object -ExpandProperty Properties
 
<#
Initializing an object named objADSearcher of type System.DirectoryServices.DirectorySearcher
Setting the filter property to search for computers with the cn of the current computername
Calling the function FineOne() of objADSearcher and storing the result in $myComputerInAD
Piping the result of $myComputerInAD into Format-List
 
This returns a hashtable of properties and values of all information retrieved from Active Directory for this object.
 
Name                           Value
----                           -----
logoncount                     {4060}
codepage                       {0}
objectcategory                 {CN=Computer,CN=Schema,CN=Configuration,DC=abc...
description                    {Rubens Computer}
operatingsystem                {Windows 7 Enterprise}
usnchanged                     {153583297}
instancetype                   {4}
name                           {CN100237}
badpasswordtime                {0}
pwdlastset                     {131604486016794242}
serviceprincipalname           {WSMAN/CN0100237.abc.de, WSMAN/CN0100237...
objectclass                    {top, person, organizationalPerson, user...}
badpwdcount                    {0}
samaccounttype                 {805306369}
lastlogontimestamp             {131613117029854487}
usncreated                     {76836641}
operatingsystemservicepack     {Service Pack 1}
objectguid                     {166 202 87 110 156 88 131 74 189 190 69 28 38 2 ...
localpolicyflags               {0}
whencreated                    {6/3/2015 8:18:34 AM}
adspath                        {LDAP://CN=CN100237,OU=IT,OU=Dept Computi...
…
#>
  • NameSpace: DirectoryServices
  • Example: DirectorySearcher—search Active Directory without doing so from any domain-joined Windows computer and without having administrative tools installed.
  • Scenario: Retrieving all objects (computer, groups, users, etc. ) that contain *admin* in their name
  • Code:
$againADSearcher = [adsisearcher]""
$againADSearcher.Filter = "Name=*admin*"
$againADSearcher.FindAll()

<#
Initiates an empty object of type System.DirectoryServices.DirectorySearcher and stores it in $againADSearcher. Sets the filter property to get all objects that have *admin* in the Name attribute.

The function FindAll() returns all found objects.
#>

Text.RegularExpressions.Regex ^

  • NameSpace: Text.RegularExpressions.Regex
  • Example: Matches—return the results after applying a regular expression to text
  • Scenario: You need to know all matches of the statement you're looking for in a text
  • Code:
$text = @'
This line doesn't matter.
Something about kb1234567, a critical one.
Doesn't count either...
Kb6635242 occurs here.
'@

$pattern = '(?i)KB\d{6,8}'
[RegEx]::Matches($text, $pattern).Value

#Returns:
#kb1234567
#Kb6635242
<#

[Regex] initiates an object of the type System.Text.RegularExpressions.Regex. Matches is a function called here with two parameters. The first is the text to scan, and the second parameter is the pattern to use for searching. The result is a list of objects where the ‘value’ property contains only the desired text.

PowerShell provides the -match operator we can use to retrieve results from regular expressions. However -match only returns the first match. In this example it would return only ‘kb1234567’.
#>
  • NameSpace: Text.RegularExpressions.Regex
  • Example: Replace—replace all matches with something else
  • Scenario: You need to replace the 'KB' that belongs to a hotfix name with 'PatchId:'
  • Code:
$text = @'
This line doesn't matter.
Something about kb1234567, a critical one.
Doesn't count either...
Kb6635242 occurs here.
'@

$code =
{
       param($match)
       ($match.Groups[0].Value) -replace('[kK][bB]','PatchId: ')
}

[RegEx]::Replace($text, $pattern, $code)

#Returns:
#This line doesn't matter.
#Something about PatchId: 1234567, a critical one.
#Doesn't count either...
#PatchId: 6635242 occurs here.
<#
[Regex] initiates an object of the type System.Text.RegularExpressions.Regex. ‘Replace’ is a function called here with three parameters. The first is the text to scan, and the second is the pattern to use for searching. The last parameter stands for the script block to call on a match.

The script block here receives the matching content that replaces the characters ‘KB’ with ‘PatchId:’.
#>
avatar

Discussion (0)

There are no comments for this doc yet.

Leave a Reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *

© 4sysops 2006 - 2021

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account