在PowerShell中等效于C#的"using"关键字?

fro*_*h42 74 .net powershell powershell-2.0

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

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

...


  var blurb = new Thingamabob();

...
Run Code Online (Sandbox Code Playgroud)

那么在Powershell中有一种方法可以做类似的事情吗?我正在访问很多.net对象,并且不喜欢打字

 $blurb = new-object FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It.Thingamabob;
Run Code Online (Sandbox Code Playgroud)

每时每刻.

dah*_*byk 56

这样的命名空间级别真的没什么.我经常将常用类型分配给变量然后实例化它们:

$thingtype = [FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It.Thingamabob];
$blurb = New-Object $thingtype.FullName
Run Code Online (Sandbox Code Playgroud)

如果不重复使用该类型可能不值得,但我相信这是你能做的最好的.


Bra*_*bby 38

PowerShell 5.0(包含在WMF5或Windows 10及更高版本中)将该using namespace构造添加到该语言中.您可以在脚本中使用它,如下所示:

#Require -Version 5.0
using namespace FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It
$blurb = [Thingamabob]::new()
Run Code Online (Sandbox Code Playgroud)

(#Require第一行上的语句不需要使用using namespace,但它会阻止脚本在PS 4.0及以下版本中运行,这using namespace是语法错误.)

  • 知道#Require 语句很方便,谢谢。 (2认同)

Ric*_*erg 12

查看几年前的这篇博客文章:http://blogs.msdn.com/richardb/archive/2007/02/21/add-types-ps1-poor-man-s-using-for-powershell.aspx

这是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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并且,使用它:

RICBERG470> $tfs | add-types "Microsoft.TeamFoundation.VersionControl.Client"
RICBERG470> $itemSpec = new-object $tfs.itemspec("$/foo", $tfs.RecursionType::none)
Run Code Online (Sandbox Code Playgroud)

基本上我所做的是为非重要类型抓取程序集,然后编写一个使用Add-Member的"构造函数"(以结构化方式)将它们添加到我关心的对象中.

另见后续帖子:http://richardberg.net/blog/?p = 38


小智 7

这只是一个玩笑,开玩笑......

$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
Run Code Online (Sandbox Code Playgroud)


Jos*_*osh 5

以下是一些在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)
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)


bou*_*err 5

如果只需要创建类型的实例,则可以将长命名空间的名称存储在字符串中:

$st = "System.Text"
$sb = New-Object "$st.StringBuilder"
Run Code Online (Sandbox Code Playgroud)

它没有usingC#中的指令那么强大,但至少它很容易使用.