C# in PowerShell: Language Mode Not Supported - c#

I am trying to get a very simple script to work in PowerShell, and it keep popping back with the following error:
Add-Type : Cannot add type. Definition of new types is not supported in this language mode.
At C:\Users\jdkin_000.ATHENA\cs_init.ps1:16 char:1
+ Add-Type -TypeDefinition $Source -Language CSharp
Here is the script:
$Source = #"
using System;
namespace cs1
{
public class Program
{
public static void Main()
{
Console.WriteLine("Hello world!");
}
}
}
"#
Add-Type -TypeDefinition $Source -Language CSharp
Any suggestions on how to get this script to work on the exact device that is throwing back the error. The script and similar scripts work on other machines, but when the script contains C#, this machine just doesn't want to play fair.

Try running this:
$ExecutionContext.SessionState.LanguageMode
Here is the link explaining the LanguageMode. I assume you are in a mode that restricts the ability to define new types.
https://technet.microsoft.com/en-us/library/dn433292.aspx
Edit: Based on the Windows RT 8.1 OS, (
Windows RT Powershell (PermissionDenied) on New-Object)
It doesn't appear that it can be done.

Powershell also may switch to ConstrainedLanguage mode when there is no space available on system drive.

Related

PowerShell and LuaInterface.dll

LuaInterface
Here is an example on c#
Im newbie. How is properly to call this dll?
I was trying this:
[System.Reflection.Assembly]::LoadFile("E:\\lua\\LuaInterface.dll")
$Lua = new-object LuaInterface.Lua # Here IntelliSense see class lua after dot
$lua.DoString("local a=5") # Here IntelliSense see all methods after dot
And this:
Add-Type -path "E:\lua\LuaInterface.dll"
[LuaInterface.Lua]::DoString("local a=5")
But unsuccessfully. Pls, show me example of "3+2" from LuaInterface.
Methods from class Lua PS somehow cant see.
On screenshot powershell can see methods from luaDLL class. But there needed always one more parameter luastate.
You're really close, but :: is only for static member access.
I got the following working in a 32-bit console (PowerShell 5.1):
# Load LuaInterface
Add-Type -Path path\to\luainterface.dll
# Create Lua instance
$lua = [LuaInterface.Lua]::new()
# Set global variable values
$lua['a'] = 2
$lua['b'] = 3
# return result of `a+b`
$lua.DoString("return a+b")

Get input from the user using ReadLine in c# code that runs as part of PowerShell script in PowerShell ISE

I need to prompting users for input in C# part of the code, but it doesn't work for me (gets empty input automagically) when run from PowerShell ISE. Code works as expected when run from just regular PowerShell command prompt (asks for the name)
$id = get-random
$code = #"
using System;
using System.Linq;
namespace Application
{
public class Program$id
{
public static void Main()
{
Console.WriteLine("Please enter your sweet name....");
String name = Console.ReadLine();
Console.WriteLine("Hello *"+name+" %" );
}
}
}
"#
Add-type -TypeDefinition $code -Language CSharp
iex "[Application.Program$id]::Main()"
When run in ISE the output is following (notice there is no chance to provide input):
PS C:\Users\Pavithra Kathirvel\Desktop> C:\Users\Pavithra Kathirvel\Desktop\demo.ps1
Please enter your sweet name....
Hello * %
As a beginner start with the basics in C# and powershell. If you are able to use one, it will be easier for you to learn the other. Also there are parts, which are in powershell faster than in c# and less code.
If you still want to execute your C# code in powershell, have a look at this link, it will run the script from a .cs file
Run a C# .cs file from a PowerShell Script
Also here is a really good tutorial for using c# in powershell:
https://blog.adamfurmanek.pl/2016/03/19/executing-c-code-using-powershell-script/

Execute C# code directly from Otter script

I've been working with Otter script for a bit now, and I'd like to execute C# code directly from one of my plans. I know I can execute PowerShell code directly using PSExec, but is there an equivalent for C# like CSExec or similar?
Here is the code I would like to run:
if (Directory.Exists($Path))
LonUtil.SendEmail("Path exists!");
else
LonUtil.SendEmail("Path does not exist.", false);
You could create a new type in Powershell and call the code directly from there using PSExec:
$source = #"
public class MyCode
{
public void Action(string path)
{
System.Console.WriteLine(path);
}
}
"#
Add-Type -TypeDefinition $source
$MyCode = New-Object MyCode
$MyCode.Action("Write this to the console!")
Alternatvely, compile that c# code into an assembly, say MyApplication.exe, and then write a powershell script which executes the program:
$path = "the/required/path"
& MyApplication.exe $path
Then use PSExec from Otter Script to run the above bit of Powershell

powershell embedded c# using ObservableCollection

I am trying to add a type in powershell from c# code that uses an observablecollection. I've tried for a day or two and I can't get anything to work.
What I was trying to come up with was a view model for wpf without relying on any kind of extra powershell modules.
This is the latest I've come up with:
$code = #"
using System;
using System.Collections.ObjectModel;
namespace Test
{
public class TestClass
{
public ObservableCollection<string> Items { get; set; }
public TestClass()
{
Items = new ObservableCollection<string>();
}
}
}
"#
Add-Type -TypeDefinition $code -ReferencedAssemblies #("WindowsBase") -Language CSharpVersion3
I can't get past an error of:
Add-Type : c:\Users\ncollier\AppData\Local\Temp\wjq4ciwc.0.cs(9) : The type or namespace name 'ObservableCollection' could not be found (
are you missing a using directive or an assembly reference?)
Edit
I'm trying to run this in powergui, but if I run it in the powershell ISE maybe it works... Is there something I could be doing wrong in powergui?
try just :
Add-Type -TypeDefinition $code
In my box I can add type.
Edit after comment:
I discovered that using powershell.exe.config ( or for ISE powershell_ise.exe.config) to load .net 4.0 there's no needs to add ReferencedAssemblies (in this code, others situations needs reference system.core or may needs others assembly references ). I suspect that also PowerGui load .net 4.0 but I can test it.
You can try on PowerGui this:
[appdomain]::currentdomain.getassemblies()
and see if there are assemblies version 4.0.xxxx

How to convert C# code to a PowerShell Script?

I regularly have to convert an existing C# code snippet/.CS file to a PowerShell script. How could I automate this process?
While I am aware that there are methods that can convert a .cs file to a cmdlet, I'm only interested in converting the C# code to a script or module.
I know you're looking for something that somehow converts C# directly to PowerShell, but I thought this is close enough to suggest it.
In PS v1 you can use a compiled .NET DLL:
PS> $client = new-object System.Net.Sockets.TcpClient
PS> $client.Connect($address, $port)
In PS v2 you can add C# code directly into PowerShell and use it without 'converting' using Add-Type (copied straight from MSDN )
C:\PS>$source = #"
public class BasicTest
{
public static int Add(int a, int b)
{
return (a + b);
}
public int Multiply(int a, int b)
{
return (a * b);
}
}
"#
C:\PS> Add-Type -TypeDefinition $source
C:\PS> [BasicTest]::Add(4, 3)
C:\PS> $basicTestObject = New-Object BasicTest
C:\PS> $basicTestObject.Multiply(5, 2)
There is a Reflector add-in for PowerShell that will allow you to see the corresponding PowerShell script for static methods on classes
There's a good post with the example: http://blogs.msmvps.com/paulomorgado/2009/09/17/powershell-for-the-net-developer/.
PowerShell Pro Tools for Visual Studio have a feature to convert C# code in a PowerShell script.

Categories