Maxim Petrov
Maxim Petrov

Reputation: 309

Doesn't load assembly in powershell

I try execute c# in powershell. I wrote script, but it doesn't work. This script contain in c# hello simple class for test. In future I need work with XML. And that's why I add System.XML.

Source = @"
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConverterTRX
{
    public class PS
    {
        public static string Convert()
        {
            XmlSerializer xmlSer = new XmlSerializer(typeof(string));
            return "Convert1";
        }
        public static string Convert1(string path)
        {
            return "Convert2="+path+"/123";
        }
    }
}
"@
if (-not ([System.Management.Automation.PSTypeName]'PS').Type)
{
    Add-Type -AssemblyName Microsoft.CSharp
    Add-Type -AssemblyName System
    Add-Type -AssemblyName System.Core
    Add-Type -AssemblyName System.Data
    Add-Type -AssemblyName System.Data.DataSetExtensions
    Add-Type -AssemblyName System.Xml
    Add-Type -AssemblyName System.Xml.Linq
    Add-Type  -TypeDefinition $Source -Language CSharp
}
"Call function"
[ConverterTRX.PS]::Convert()

This script throw exception:

Add-Type : *\Temp\zktiv5n4.0.cs(3) : The type or namespace name 'Xml' does not exist in the namespace 'System' (are you missing an assembly reference?)
*\Temp\zktiv5n4.0.cs(2) : using System.IO;
*\Temp\zktiv5n4.0.cs(3) : >>> using System.Xml;
*\Temp\zktiv5n4.0.cs(4) : using System.Xml.Serialization;

So, how it's fix?

Upvotes: 1

Views: 2129

Answers (1)

Vesper
Vesper

Reputation: 18747

You need to add -ReferencedAssemblies parameter to Add-Type cmdlet call, otherwise you'll not get namespaces.

$referencingassemblies = ("C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.XML.dll")
Add-Type  -TypeDefinition $Source -ReferencedAssemblies $referencingassemblies -Language CSharp

Upvotes: 3

Related Questions