相當於c#在powershell中的“using”關鍵字?

[英]Equivalent to C#'s “using” keyword in powershell?


When I use another object in the .net-Framework in C# I can save a lot of typing by using the using directive.

當我在c# .net框架中使用另一個對象時,我可以通過使用using指令節省大量的輸入。

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

...


  var blurb = new Thingamabob();

...

So is there a way in Powershell to do something similiar? I'm accessing a lot of .net objects and am not happy of having to type

那么,在Powershell中是否有類似的方法呢?我訪問了很多。net對象,不喜歡輸入。

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

all the time.

所有的時間。

9 个解决方案

#1


12  

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

看看幾年前的這篇博文:http://blogs.msdn.com/richardb/archive/2007/02/21/add-types-ps1-poor-man-s- use -for powershell.aspx

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

這是add-types。ps1,摘自那篇文章:

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.

基本上,我所做的就是為非平凡類型遍歷程序集,然后編寫一個“構造函數”,使用add - member(以結構化的方式)將它們添加到我關心的對象中。

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

另請參閱以下文章:http://richardberg.net/blog/?

#2


54  

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.

如果類型不重復使用,可能不值得這樣做,但我相信這是最好的方法。

#3


26  

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:

PowerShell 5.0(包含在WMF5或Windows 10及以上版本中)將using命名空間構造添加到語言中。你可以在你的劇本中這樣使用:

#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.)

(第一行的#Require語句不需要使用名稱空間,但它將阻止腳本在PS 4.0中運行,在下面使用名稱空間是語法錯誤。)

#4


6  

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

#5


5  

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.

下面是一些在PowerShell 2.0中工作的代碼,可以添加類型別名。但問題是它沒有作用域。有了一些額外的工作,您可以“不導入”名稱空間,但是這應該會讓您有一個好的開始。

##############################################################################
#.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)
            }
        }

    }

}

#6


4  

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.

它沒有c#中的using指令那么強大,但至少它很容易使用。

#7


2  

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.

你所有的回答讓我走上了一條最有希望的道路:在他的博客文章中,Keith Dahlby提出了一個Get-Type commandlet,允許對泛型方法進行簡單的類型組合。

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

我認為沒有理由禁止exetend將其也用於搜索一個類型的預定義程序集路徑。

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.

這將產生一個不錯的Thingamabob通用列表。當然,我將把沒有路徑定義的所有東西都打包到另一個實用函數中。擴展get類型將包含一個步驟,用於解決路徑上的任何給定類型。

#8


0  

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

#9


-2  

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

我知道這是一篇老文章,但我也在尋找同樣的東西,並偶然發現了這篇文章:http://weblogs.asp.net/adweigert/powershell-adding-using-statement

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

編輯:我想我應該指定它允許您使用熟悉的語法……

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/06/26/729fbf7447bb7a70f11e3d4dc32a24c6.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com