0

我正在尝试在 PowerShell 中使用自定义 .NET 程序集运行 C# 代码,但无法使其正常工作。

这是我的代码:

# Adding custom assemblies to the PowerShell assemblies
Add-Type -Verbose -Path "C:\MyCustomAssembly.dll"

# Adding reference of standard .NET assemblies 
$Refs = @("C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Xml.dll",
"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Data.Entity.dll",
"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Runtime.Serialization.dll")

$Source = @"
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using MyCustomAssembly;

namespace CSharpCode
{
    public class WebClient
    {
        public void ConsumePostMethod()
        { ... }
    }
}
"@

Add-Type -ReferencedAssemblies $Refs -TypeDefinition $Source -Language CSharp -PassThru

[CSharpCode.WebClient]::ConsumePostMethod()

这是我得到的错误:

Add-Type : c:\Users\MyUser\AppData\Local\Temp\znllnhvt.0.cs(5) : The type or namespace name 'MyCustomAssembly' could not be found (are you missing a using directive 
or an assembly reference?)
c:\Users\MyUser\AppData\Local\Temp\znllnhvt.0.cs(4) : using System.Runtime.Serialization;
c:\Users\MyUser\AppData\Local\Temp\znllnhvt.0.cs(5) : >>> using MyCustomAssembly;
c:\Users\MyUser\AppData\Local\Temp\znllnhvt.0.cs(6) : 
At line:109 char:1
+ Add-Type -ReferencedAssemblies $Refs -TypeDefinition $Source -Language CSharp -P ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (c:\Users\MyUser...bly reference?):CompilerError) [Add-Type], Exception
    + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

Add-Type : Cannot add type. There were compilation errors.
At line:109 char:1
+ Add-Type -ReferencedAssemblies $Refs -TypeDefinition $Source -Language CSharp -P ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Add-Type], InvalidOperationException
    + FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand

Unable to find type [CSharpCode.WebClient]: make sure that the assembly containing this type is loaded.
At line:111 char:1
+ [CSharpCode.WebClient]::ConsumePostMethod()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (CSharpCode.WebClient:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

奇怪的是,如果我在下面运行这个命令,它表明 MyCustomAssembly.dll 已加载到会话中。有人可以帮忙吗?!

[System.AppDomain]::CurrentDomain.GetAssemblies() | Where {$_.Location} | ForEach {Split-Path -Leaf $_.Location} | Sort

Accessibility.dll
MyCustomAssembly.dll
Microsoft.Build.Framework.dll
Microsoft.CSharp.dll
...
4

1 回答 1

3

Add-Type不使用任何当前加载的程序集作为隐式引用。因此,如果您想在Add-Type源代码中使用自定义程序集中的任何类型,那么您应该将此程序集-ReferencedAssemblies显式添加到参数中。

于 2015-05-20T17:05:39.140 回答