在Powershell中使用命名空间

在回答这个问题时想到了这个问题 。

你怎样才能避免在命名空间中完全限定每一种types?

编写System.Security.Cryptography.X509Certificates.X509Store而不是X509Store ,或者[System.Security.Cryptography.X509Certificates.StoreName]::My而不是[StoreName]::My真的非常繁琐。

在C#中你有using指令…那么Powershell呢?


编辑1 – 这适用于types:

 $ns = "System.Security.Cryptography.X509Certificates" $store = New-Object "$ns.X509Store"(StoreName,StoreLocation) 

New-Object将string字面量作为types定义,因此可以通过编程方式构build。


编辑2 – 这适用于枚举成员用作参数:

 $store = New-Object "$ns.X509Store"("My","LocalMachine") 

其中“我的”是[System.Security.Cryptography.X509Certificates.StoreName]::My和“LocalMachine”是[System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine
文字名称自动转换为枚举成员,如果放置在预期的枚举成员的地方。

对于枚举,您不必指定整个types的名称。 例如:

你可以这样做:

 New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext([System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Domain) 

或者更简单的版本:

 New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain') 

您可以使用string来标识要使用的枚举,而不必使用装饰完整的名称。 PowerShell处理types转换,将string转换为枚举值。 使用上面显示的具体示例,这意味着您可以执行此操作:

 [System.Security.Cryptography.X509Certificates.OpenFlags]'ReadWrite' 

Powershell将正确地转换它(所以将'ReadWrite'传递给一个OpenFlags枚举值的参数可以正常工作)。 如果你想传递多个值,你可以这样做:

 [System.Security.Cryptography.X509Certificates.OpenFlags]@('ReadWrite','IncludeArchived') 

请注意,我将这些命令添加为types名称的前缀,但是如果您将它们传递给某个types化的参数,则只需将其忽略即可。

这应该让你更近一步,能够编写脚本,使用特定的命名空间,而不必装饰所有的名字。

我知道,这有点迟,但PowerShell v5增加了很多很酷的语言。 其中之一是“使用命名空间”。

 PS> using namespace System.Security.Cryptography.X509Certificates; [X509Store] IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False X509Store System.Object 

正确的方式?

 $_m = [math] $_m::sin((45*($_m::pi/180))) 

这似乎工作:

 [Reflection.Assembly]::Load("System.Security, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a") $stoopidnamespace = 'System.Security.Cryptography.X509Certificates.X509Store' New-Object $stoopidnamespace($null) 

但是这样做很丑陋:

 $stoopidnamespace = 'System.Security.Cryptography.X509Certificates' New-Object $stoopidnamespace'.X509Store'($null)