繁体   English   中英

从Powershell脚本引用.Net .dll

[英]Reference .Net .dll from powershell script

您能帮我从Powershell脚本中引用.Net .dll吗? 我正在使用Powershell ISE编写/调试脚本。 我有一些.net代码引用了其中的Nuget包,我想将该代码嵌入到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 

您可以使用Add-Type片段加载DLL:

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/

我已经找到问题的解决方案,需要在引用程序集之前进行Add-Type来注册另一种类型。 下面是我的更新代码。

 $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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM