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

前端 未结 9 1937
臣服心动
臣服心动 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

提交回复
热议问题