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

前端 未结 9 1785
臣服心动
臣服心动 2020-12-04 14:13

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

using FooCompany.Bar.Qux.Assembly.With.Ridicul         


        
相关标签:
9条回答
  • 2020-12-04 14:57

    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

    0 讨论(0)
  • 2020-12-04 15:03

    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.

    0 讨论(0)
  • 2020-12-04 15:03

    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) { ... }
    
    0 讨论(0)
提交回复
热议问题