当我运行 system.security 命名空间时,出现此错误。这就是我所追求的
$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")
New-Object: Cannot find type [System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")]: make sure the assembly containing this type is loaded.
At line:1 char:19
+ $cert = New-Object <<<<
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand**
我做错了什么?
尝试运行此命令以查看是否已加载 System.dll(默认情况下应该是):
[AppDomain]::CurrentDomain.GetAssemblies() |
Where {$_.Location -match '\\System\\'}
如果已加载,则此命令应显示
X509Certificate2
类型:
[AppDomain]::CurrentDomain.GetAssemblies() |
Where {$_.Location -match '\\System\\'} |
%{$_.GetExportedTypes()} | Where {$_.Name -match 'X509Cert'}
如果 System.dll 未加载(这会很奇怪),请尝试加载它:
Add-Type -AssemblyName System
请参阅:http://technet.microsoft.com/en-us/library/hh849914.aspx
仅供参考...我收到错误:
Unable to find type [System.Security.Cryptography.x509Certificates.X509Certificate2UI]
使用时:
$certSelect = [System.Security.Cryptography.x509Certificates.X509Certificate2UI]::SelectFromCollection($certCollection, $title, $msg, 0)
但是,我之前在脚本中创建集合时没有错误:
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
为了使错误消失,我必须在早些时候的某个时候包含以下内容:
Add-Type -AssemblyName System.Security
我在 ISE 中遇到了这个问题(但似乎也适用于普通命令窗口),并且似乎使用自动完成功能会自动
Add-Type
满足您要查找的任何内容。如果您启动一个新实例并运行:
[AppDomain]::CurrentDomain.GetAssemblies() | grep Security
它不会返回
System.Security
,但如果您随后输入此内容并让智能感知完成其工作:
[System.
然后您可以再次运行此命令:
[AppDomain]::CurrentDomain.GetAssemblies() | grep Security
然后它会返回
System.Security
。因此,这就是为什么您可以编写一个运行良好的脚本,然后稍后重新访问它,但它却损坏了。使用智能感知并不能修复你的脚本,相反你必须添加这一行:
Add-Type System.Security
或者任何未自动添加的库(似乎需要 dll 文件名,例如
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Security.dll
)。
我很确定 IseSteroids(付费 ISE 插件)可以检测到这一点,也许其他的也可以。
我已经解决了我的问题。这很容易:
cd\
$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")
cd\ 是必要的