相当于 C # 的“使用”关键字在 Powershell?

中使用另一个对象时,。Net-Framework 在 C # 中,使用 using 指令可以节省大量的输入。

using FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It;


...




var blurb = new Thingamabob();


...

那么,Powershell 有没有类似的办法呢?我访问了很多。对象,并且不喜欢不得不输入

 $blurb = new-object FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It.Thingamabob;

一直都是。

42498 次浏览

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.

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

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

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

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

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

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

Here is how 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 nice generic List of Thingamabob. Of course I'd wrap up everthing sans the path definition in just another utility function. The extended get-type would include a step to resolve any given type agains the path.

Here's some code that works in PowerShell 2.0 to add type aliases. But the problem is that it is not scoped. With some extra work you could "un-import" the namespaces, but 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)
}
}


}


}

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

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

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

I realize this is an old post, but I was looking for the same thing and came across this: http://weblogs.asp.net/adweigert/powershell-adding-the-using-statement

Edit: I suppose I should specify that it allows you to use the familiar syntax of...

using ($x = $y) { ... }

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.0
using 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.)

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