PowerShell using Statement

Image Description

Daily PowerShell #3

Scripting Language Daily PowerShell

October 20, 2021

The using statement can be used for referencing namespaces, importing modules or loading assemblies. The using statement must appear at the top of the script.

Referencing Namespaces

When specifying the using with a namespace, it will allow you to use just the type name when creating objects or referencing static methods or properties within you script. It can thus shorten the script significantly.

using namespace System.IO

$Bytes = [File]::ReadAllBytes('C:\myFile.txt')

Importing Modules

Instead of using Import-Module, you can specify a using statement to import modules. Doing so will also import all PowerShell classes defined within the root module of the module.

using module MyModule

Loading .NET Assemblies

You can also use using to load .NET assemblies.

using assembly C:\myDll.dll