Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Shorten namespace names so it's easier to access types

Is there a method of shortening PowerShell namespace references?

Typing [RootNameSpace1.NameSpace2.Namepsace3+SomeEnum]::SomeValue is taxing and not a very good user expierence. I realize that you can reference System level objects without a namespace such that [Type]::GetType(... will work. Is there some manifest I could create or command I could use to shorten lengthy namespaces?

like image 919
Adam Driscoll Avatar asked May 26 '10 16:05

Adam Driscoll


2 Answers

Any methods accepting Enums will accept strings, but this is for Enums only and where there is no ambiguity (meaning there are no other overloads with a signature matching strings in this fashion.)

If you're on powershell v2.0, you can (ab)use Type Accelerators. I blogged about this before, and Joel Bennett wrapped up my technique in a handy script:

http://poshcode.org/1869

UPDATE (2020): this link is broken, but for current versions of powershell there is an easier way.

using namespace System.Collections.Generic;
$list = new-object List # also: $list = [list]::new()

-Oisin

like image 105
x0n Avatar answered Sep 19 '22 12:09

x0n


Lengthy types can be assigned to variables and then used via those variables:

# enum values
$rvk = [Microsoft.Win32.RegistryValueKind]
$rvk::Binary
$rvk::DWord

# static members
$con = [System.Console]
$con::CursorLeft
$con::WriteLine('Hello there')

# just to be sure, look at types
.{
    $rvk::Binary
    $con::WriteLine
    $con::CursorLeft
} |
% { $_.GetType() }
like image 40
Roman Kuzmin Avatar answered Sep 19 '22 12:09

Roman Kuzmin