Equivalent to C#'s "using" keyword in powershell? Equivalent to C#'s "using" keyword in powershell? powershell powershell

Equivalent to C#'s "using" keyword in powershell?


There's really nothing at the namespace level like that. I often assign commonly used types to variables and then instantiate them:

$thingtype = [FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It.Thingamabob];$blurb = New-Object $thingtype.FullName

Probably not worth it if the type won't be used repeatedly, but I believe it's the best you can do.


PowerShell 5.0 (included in WMF5 or Windows 10 and up), adds the using namespace construct to the language. You can use it in your script like so:

#Require -Version 5.0using namespace FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It$blurb = [Thingamabob]::new()

(The #Require statement on the first line is not necessary to use using namespace, but it will prevent the script from running in PS 4.0 and below where using namespace is a syntax error.)


Check out this blog post from a couple years ago: http://blogs.msdn.com/richardb/archive/2007/02/21/add-types-ps1-poor-man-s-using-for-powershell.aspx

Here is add-types.ps1, excerpted from that article:

param(    [string] $assemblyName = $(throw 'assemblyName is required'),    [object] $object)process {    if ($_) {        $object = $_    }    if (! $object) {        throw 'must pass an -object parameter or pipe one in'    }    # load the required dll    $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assemblyName)    # add each type as a member property    $assembly.GetTypes() |     where {$_.ispublic -and !$_.IsSubclassOf( [Exception] ) -and $_.name -notmatch "event"} |     foreach {         # avoid error messages in case it already exists        if (! ($object | get-member $_.name)) {            add-member noteproperty $_.name $_ -inputobject $object        }    }}

And, to use it:

RICBERG470> $tfs | add-types "Microsoft.TeamFoundation.VersionControl.Client"RICBERG470> $itemSpec = new-object $tfs.itemspec("$/foo", $tfs.RecursionType::none)

Basically what I do is crawl the assembly for nontrivial types, then write a "constructor" that uses Add-Member add them (in a structured way) to the objects I care about.

See also this followup post: http://richardberg.net/blog/?p=38