问题
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.
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
回答1:
You can use the Add-Type
snippet to load DLL's:
Add-Type -Path "$path\NuGet.Configuration.dll"
Add-Type -Path "$path\System.Core.dll"
Add-Type -Path "$path\System.dll"
.Net DLL's can be added like this:
Add-Type -AssemblyName System.ServiceProcess
Check: https://blogs.technet.microsoft.com/heyscriptingguy/2010/11/11/use-powershell-to-work-with-the-net-framework-classes/
回答2:
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
来源:https://stackoverflow.com/questions/39827064/reference-net-dll-from-powershell-script