[ACCEPTED]-Equivalent to C#'s "using" keyword in powershell?-powershell-2.0

Accepted answer
Score: 59

There's really nothing at the namespace 5 level like that. I often assign commonly 4 used types to variables and then instantiate 3 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 2 be used repeatedly, but I believe it's the 1 best you can do.

Score: 49

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

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

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

Score: 12

Check out this blog post from a couple years 6 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 5 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 4 assembly for nontrivial types, then write 3 a "constructor" that uses Add-Member 2 add them (in a structured way) to the objects 1 I care about.

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

Score: 8

this is just a joke, joke...

$fullnames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType( [String]) );

function using ( $name ) { 
foreach ( $type in [Reflection.Assembly]::LoadWithPartialName($name).GetTypes() )
    {
        $fullnames.Add($type.fullname);
    }
}

function new ( $name ) {
    $fullname = $fullnames -like "*.$name";
    return , (New-Object $fullname[0]);
}

using System.Windows.Forms
using FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It
$a = new button
$b = new Thingamabob

0

Score: 5

Here's some code that works in PowerShell 4 2.0 to add type aliases. But the problem 3 is that it is not scoped. With some extra 2 work you could "un-import" the namespaces, but 1 this should get you off to a good start.

##############################################################################
#.SYNOPSIS
# Add a type accelerator to the current session.
#
#.DESCRIPTION
# The Add-TypeAccelerator function allows you to add a simple type accelerator
# (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
#
#.PARAMETER Name
# The short form accelerator should be just the name you want to use (without
# square brackets).
#
#.PARAMETER Type
# The type you want the accelerator to accelerate.
#
#.PARAMETER Force
# Overwrites any existing type alias.
#
#.EXAMPLE
# Add-TypeAccelerator List "System.Collections.Generic.List``1"
# $MyList = New-Object List[String]
##############################################################################
function Add-TypeAccelerator {

    [CmdletBinding()]
    param(

        [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
        [String[]]$Name,

        [Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$true)]
        [Type]$Type,

        [Parameter()]
        [Switch]$Force

    )

    process {

        $TypeAccelerators = [Type]::GetType('System.Management.Automation.TypeAccelerators')

        foreach ($a in $Name) {
            if ( $TypeAccelerators::Get.ContainsKey($a) ) {
                if ( $Force ) {
                    $TypeAccelerators::Remove($a) | Out-Null
                    $TypeAccelerators::Add($a,$Type)
                }
                elseif ( $Type -ne $TypeAccelerators::Get[$a] ) {
                    Write-Error "$a is already mapped to $($TypeAccelerators::Get[$a])"
                }
            }
            else {
                $TypeAccelerators::Add($a, $Type)
            }
        }

    }

}
Score: 5

If you just need to create an instance of 4 your type, you can store the name of the 3 long namespace in a string:

$st = "System.Text"
$sb = New-Object "$st.StringBuilder"

It's not as powerful 2 as the using directive in C#, but at least it's 1 very easy to use.

Score: 2

Thanks everybody for your input. I've marked 16 Richard Berg's contribution as an answer, because 15 it most closely resembles what I'm looking 14 for.

All your answers brought me on the track 13 that seems most promising: In his blog post Keith Dahlby 12 proposes a Get-Type commandlet that allows 11 easy consutruction of types for generic 10 methods.

I think there is no reason against 9 exetending this to also search through a 8 predefined path of assemblies for a type.

Disclaimer: I 7 haven't built that -- yet ...

Here is how 6 one could use it:

$path = (System.Collections.Generic, FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It)

$type = get-type -Path $path List Thingamabob
$obj = new-object $type
$obj.GetType()

This would result in a 5 nice generic List of Thingamabob. Of course 4 I'd wrap up everthing sans the path definition 3 in just another utility function. The extended 2 get-type would include a step to resolve 1 any given type agains the path.

Score: 0
#Requires -Version 5
using namespace System.Management.Automation.Host
#using module

0

More Related questions