.net 相当于powershell中C#的“using”关键字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1048954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equivalent to C#'s "using" keyword in powershell?
提问by froh42
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? 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.
每时每刻。
采纳答案by Brant Bobby
PowerShell 5.0 (included in WMF5 or Windows 10 and up), adds the using namespaceconstruct to the language. You can use it in your script like so:
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()
(The #Requirestatement 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 namespaceis a syntax error.)
(#Require第一行的语句不需要使用using namespace,但它会阻止脚本在 PS 4.0 及以下版本中运行,如果using namespace出现语法错误。)
回答by dahlbyk
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.
如果类型不会重复使用,可能不值得,但我相信这是你能做的最好的。
回答by Richard Berg
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
回答by Richard Berg
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
回答by Josh
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)
}
}
}
}
回答by bouvierr
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 usingdirective in C#, but at least it's very easy to use.
它没有usingC# 中的指令那么强大,但至少它非常易于使用。
回答by froh42
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 postKeith 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. 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-type 将包括一个步骤来重新解析路径中的任何给定类型。
回答by Jaqueline Vanek
#Requires -Version 5
using namespace System.Management.Automation.Host
#using module
回答by haliphax
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) { ... }

