I am attempting to run some c# code through powershell (just for fun). I am including a short sample of the code because the actual program itself is too long and is not really the focus of this question here.
#Referencing assemblies #"referencedAssemblies", "Using" keyword equivalent in C#
$assemblies = ("System.Core", "System.Net.Http", "Newtonsoft.Json.Linq", "System.Xml.Linq","System.Data","System.Xml", "System.Data.DataSetExtensions", "Microsoft.CSharp")
Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $code -Language CSharp
$id = get-random #Workaround to allow code changes without having to load type into the same App Domain again, especially since unfortunately, you cannot unload type.
$code = @"
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
namespace Test
{
static class Program
{
static void Main(string[] args)
{
// Call the REST API method.
Console.WriteLine("\nExtracting text...\n");
ReadText(PDFFilePath).Wait();
Console.WriteLine("\nPress Enter to exit...");
Console.ReadLine();
}
}
}
"@
Add-Type -TypeDefinition $code -Language CSharp
iex "[Test.Program$id]::Main()"
I already installed Nuget and the HTTP and Newtonsoft required packages:
Install-PackageProvider Nuget –force –verbose
nstall-Module PackageManagement -Force -Repository PSGallery
Install-Package Microsoft.AspNet.WebApi.Client -SkipDependencies -verbose -ErrorAction SilentlyContinue
Install-Package Newtonsoft.Json -SkipDependencies -verbose -ErrorAction SilentlyContinue
When i run the ps1 file, i am getting the following errors:
Add-Type : Cannot bind argument to parameter 'TypeDefinition' because it is null.
Add-Type : c:\..The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)
Add-Type : c:\..The type or namespace name 'Http' does not exist in the
namespace 'System.Net' (are you missing a using directive or an assembly reference?)
why is that? i am clearly referencing the assemblies and loading them here:
$assemblies = ("System.Core", "System.Net.Http", "Newtonsoft.Json.Linq", "System.Xml.Linq","System.Data","System.Xml", "System.Data.DataSetExtensions", "Microsoft.CSharp")