从Powershell脚本引用.Net .dll [英] Reference .Net .dll from powershell script
问题描述
您能帮我从Powershell脚本中引用.Net .dll吗?我正在使用Powershell ISE编写/调试脚本.我有一些.net代码,其中引用了Nuget包,我想将该代码嵌入到powershell脚本中.
Could you please help me in referencing .Net .dll from powershell script? I'm using powershell ISE to write/debug script. I've some .net code which is referencing Nuget package in it and I want to embedded that code in powershell script.
如果我确实在C:\ WINDOWS \ system32 \ WindowsPowerShell \ v1.0和脚本的根目录(C:\ TestProjects \ UpdateLocalNugetRepository)路径中复制所需的.dll,则效果很好.我不想这样做,因为在生产中我们无法将.dll复制到system32文件夹.我知道我做错了.能否请你帮忙?以下是我的Powershell脚本-
It works well if I do copy required .dlls in C:\WINDOWS\system32\WindowsPowerShell\v1.0 and script's root(C:\TestProjects\UpdateLocalNugetRepository) path. I don't want to do that beacuse in production we can not copy .dlls to system32 folder.I know that I'm doing something wrong. Could you please help? Below is my powershell script -
$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来注册另一种类型.下面是我的更新代码.
I've found the solution for issue, need to do Add-Type before referring in assemblies to register another type. Below is my updated code.
$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
这篇关于从Powershell脚本引用.Net .dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!