Powershell – Using namespaces in Powershell

namespacesnetpowershell

Thought about it while answering this question.

How can you avoid the need to fully qualify every single type in a namespace?

It's really, really tedious to write System.Security.Cryptography.X509Certificates.X509Store instead of X509Store, or [System.Security.Cryptography.X509Certificates.StoreName]::My instead of [StoreName]::My.

In C# you have using directives… what about Powershell?


EDIT 1 – This works for types:

$ns = "System.Security.Cryptography.X509Certificates"
$store = New-Object "$ns.X509Store"(StoreName,StoreLocation)

New-Object takes a string literal as the type definition, so it can be built programmatically.


EDIT 2 – This works for enumeration members used as parametes:

$store = New-Object "$ns.X509Store"("My","LocalMachine")

Where "My" is [System.Security.Cryptography.X509Certificates.StoreName]::My and "LocalMachine" is [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine.
Literal names are automatically converted to enumeration members, if placed where an enumeration member is expected.

Best Answer

I know, it's a little bit late, but PowerShell v5 adds tons of cool language stuff. One of it is 'using namespace'.

PS> using namespace System.Security.Cryptography.X509Certificates; [X509Store]


IsPublic IsSerial Name                                     BaseType                                     
-------- -------- ----                                     --------                                     
True     False    X509Store                                System.Object                                
Related Topic