Using “Using Namespace”

by Feb 3, 2017

Working with .NET type names can be tiring because these names can be long. Here is an example:

#requires -Version 2.0

Add-Type -AssemblyName System.Speech
$speak = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$speak.Speak('Hello I am PowerShell!')

In PowerShell 5 and better, you can define the .NET namespaces you want to work with. These “using namespace” statements must be at the start of your script. Code now becomes a lot easier to read, and the using statements clarify what .NET namespaces a script is using:

#requires -Version 5.0

using namespace System.Speech.Synthesis

Add-Type -AssemblyName System.Speech

$speak = New-Object -TypeName SpeechSynthesizer
$speak.Speak('Hello I am PowerShell!')

Here is another example: the .NET namespace “System.IO.Path” contains a great number of useful path helper methods. Here are some examples:

[System.IO.Path]::ChangeExtension('test.txt', 'bat')
[System.IO.Path]::GetExtension('test.txt')

Instead of having to repeatedly use [System.IO.Path] to access these methods, you can add a “using namespace System.IO” statement and access the type via [Path] only:

#requires -Version 5.0

using namespace System.IO

[Path]::ChangeExtension('test.txt', 'bat')
[Path]::GetExtension('test.txt')

Twitter This Tip! ReTweet this Tip!