来自powershell脚本的.Net .dll参考

时间:2016-10-03 08:08:25

标签: .net powershell nuget powershell-v3.0

你能帮我从powershell脚本中引用.Net .dll吗?我使用PowerShell ISE来编写/调试脚本。我有一些引用Nuget包的.net代码,我希望将这些代码嵌入到PowerShell脚本中。

如果我在C:\ WINDOWS \ system32 \ WindowsPowerShell \ v1.0和脚本的根目录(C:\ TestProjects \ UpdateLocalNugetRepository)路径中复制所需的.dll,则效果很好。我不想在生产中这样做,我们无法将.dll复制到system32文件夹。我知道我做错了什么。能否请你帮忙? 下面是我的powershell脚本 -



$path = "C:\TestProjects\UpdateLocalNugetRepository"

$Assem =@(
        "$path\NuGet.Configuration.dll",
        "$path\System.Core.dll",
        "$path\System.dll"
         ) 

         
$Source = @” 
using NuGet.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace NuGetPSTest
{
    public class Utility
    {
 	public static async Task<bool> MyMethod(string packageName, string p1, string p2)
        {
       		//Here I use above mentioned .dll(Nuget.Configuration).
	}
    }

    
}

“@ 

Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp  



$result = [NuGetPSTest.Utility]::MyMethod(param1,param2,param3).GetAwaiter().GetResult()
$result
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以使用Add-Type代码段加载DLL&#39;

Add-Type -Path "$path\NuGet.Configuration.dll"
Add-Type -Path "$path\System.Core.dll"
Add-Type -Path "$path\System.dll"

.Net DLL可以像这样添加:

Add-Type -AssemblyName System.ServiceProcess

检查:https://blogs.technet.microsoft.com/heyscriptingguy/2010/11/11/use-powershell-to-work-with-the-net-framework-classes/

答案 1 :(得分:1)

我找到了问题的解决方案,需要在引用程序集之前执行Add-Type以注册其他类型。以下是我更新的代码。

&#13;
&#13;
$path = "C:\TestProjects\UpdateLocalNugetRepository"

Add-Type -Path "$path\NuGet.Configuration.dll"
Add-Type -Path "$path\System.Core.dll"
Add-Type -Path "$path\System.dll"

$Assem =@(
        "$path\NuGet.Configuration.dll",
        "$path\System.Core.dll",
        "$path\System.dll"
         ) 

         
$Source = @” 
using NuGet.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace NuGetPSTest
{
    public class Utility
    {
 	public static async Task<bool> MyMethod(string packageName, string p1, string p2)
        {
       		//Here I use above mentioned .dll(Nuget.Configuration).
	}
    }

    
}

“@ 

Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp  



$result = [NuGetPSTest.Utility]::MyMethod(param1,param2,param3).GetAwaiter().GetResult()
$result
&#13;
&#13;
&#13;