1

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.