简体   繁体   English

相当于powershell中C#的“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-Framework 中使用另一个对象时,我可以通过使用 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?那么 Powershell 中有没有办法做类似的事情? I'm accessing a lot of .net objects and am not happy of having to type我正在访问很多 .net 对象,但对必须键入感到不高兴

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

all the time.每时每刻。

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.如果类型不会重复使用,可能不值得,但我相信这是你能做的最好的。

PowerShell 5.0 (included in WMF5 or Windows 10 and up), adds the using namespace construct to the language. PowerShell 5.0(包含在 WMF5 或 Windows 10 及更高版本中)将using namespace结构添加到语言中。 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.) (第一行的#Require语句不是使用using namespace所必需的,但它会阻止脚本在 PS 4.0 及以下版本中运行,因为using namespace是语法错误。)

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-using-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/?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

Here's some code that works in PowerShell 2.0 to add type aliases.下面是一些可在 PowerShell 2.0 中添加类型别名的代码。 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.它不如 C# 中的using指令强大,但至少它非常易于使用。

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.我已将 Richard Berg 的贡献标记为答案,因为它与我正在寻找的最相似。

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.我认为没有理由反对将其扩展为搜索类型的程序集的预定义路径。

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.这将产生一个很好的 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.扩展的 get-type 将包括一个步骤来重新解析路径中的任何给定类型。

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

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-the-using-statement

Edit: I suppose I should specify that it allows you to use the familiar syntax of...编辑:我想我应该指定它允许您使用熟悉的语法...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM