How to convert C# code to a PowerShell Script? - c#

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.

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

C# in PowerShell: Language Mode Not Supported

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.

Run C# code on linux terminal

How can I execute a C# code on a linux terminal as a shell script.
I have this sample code:
public string Check(string _IPaddress,string _Port, int _SmsID)
{
ClassGlobal._client = new TcpClient(_IPaddress, Convert.ToInt32(_Port));
ClassGlobal.SMSID = _SmsID;
string _result = SendToCAS(_IPaddress, _Port, _SmsID );
if (_result != "") return (_result);
string _acoknoledgement = GetFromCAS();
return _acoknoledgement;
}
When I run a shell bash I use #!/bin/bash. There is how to do the same with C#?
Of course it can be done and the process is extremely simple.
Here I am explaining the steps for Ubuntu Linux.
Open terminal:
Ctrl + Alt + T
Type
gedit hello.cs
In the gedit window that opens paste the following example code:
using System;
class HelloWorld {
static void Main() {
Console.WriteLine("Hello World!");
}
}
Save and close gedit.
Back in terminal type:
sudo apt update
sudo apt install mono-complete
mcs -out:hello.exe hello.cs
mono hello.exe
Output:
Hello World!
NOTE: #adabru's answer below makes my solution obsolete unless you are using an older mono platform.
C# scripts can be run from the bash command line just like Python and Perl scripts, but it takes a small bit of bash magic to make it work. As Corey mentioned above, you must first install Mono on your machine. Then, save the following code in an executable bash script on your Linux machine:
if [ ! -f "$1" ]; then
dmcs_args=$1
shift
else
dmcs_args=""
fi
script=$1
shift
input_cs="$(mktemp)"
output_exe="$(mktemp)"
tail -n +2 $script > $input_cs
dmcs $dmcs_args $input_cs -out:${output_exe} && mono $output_exe $#
rm -f $input_cs $output_exe
Assuming you saved the above script as /usr/bin/csexec, an example C# "script" follows:
#!/usr/bin/csexec -r:System.Windows.Forms.dll -r:System.Drawing.dll
using System;
using System.Drawing;
using System.Windows.Forms;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Console");
Console.WriteLine("Arguments: " + string.Join(", ", args));
MessageBox.Show("Hello GUI");
}
}
Save the above code to a file such as "hello.cs", make it executable, change the first line to point to the previously saved bash script, and then execute it, you should see the following output along with a dialog saying "Hello GUI":
bash-4.2$ ./hello.cs foo bar baz
Hello Console
Arguments: foo, bar, baz
Note that the GUI requires that you be at run level 5. Here is a simpler C# script that runs at a pure text console:
#!/usr/bin/csexec
using System;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Console");
Console.WriteLine("Arguments: " + string.Join(", ", args));
}
}
Notice that the command line arguments are passed to the C# script, but the shebang arguments (in the first C# script above "-r:System.Windows.Forms.dll -r:System.Drawing.dll") are passed to the C# compiler. Using the latter functionality, you can specify any compiler arguments you require on the first line of your C# script.
If you are interested in the details of how the bash script works, shebang (#!) lumps together all arguments passed to it on the first line of the C# script, followed by the script name, followed by command line arguments passed to the script itself. In the first C# example above, the following 5 arguments would be passed into the bash script (delineated by quotes):
"-r:System.Windows.Forms.dll -r:System.Drawing.dll" "hello.cs" "foo" "bar" "baz"
The script determines that the first argument is not a filename and assumes it contains arguments for the C# compiler. It then strips off the first line of the C# script using 'tail' and saves the result to a temporary file (since the C# compiler does not read from stdin). Finally, the output of the compiler is saved to another temporary file and executed in mono with the original arguments passed to the script. The 'shift' operator is used to eliminate the compiler arguments and the script name, leaving behind only the script arguments.
Compilation errors will be dumped to the command line when the C# script is executed.
The #! (hashbang) tag is used to tell the shell which interpreter to use so that your perl, php, bash, sh, etc. scripts will run right.
But C# is not a scripting language, it is intended to be compiled into an executable format. You need to install at least a compiler and runtime if you want to use C#, and preferably an IDE (Integrated Development Environment) to help you develop and debug your applications.
Install Mono for the compiler and runtime, then MonoDevelop for the IDE.
After installing mono you can use csharp hello.cs. Starting with Mono 2.10, you can also use the shebang like this:
#!/usr/bin/csharp
Console.WriteLine ("Hello, World");
If you need assemblies, you can load them e.g. with the line LoadAssembly("System.IO.Compression") inside your script.
Reference: man csharp.
You can't execute C# like a script, you have to compile it first. For that, you could install mono.
You can then compile your program with mcs and execute it with mono.
First, you have to install mono
sudo apt install mono-complete
Commands to execute
mcs -out:$1.exe $1.cs
mono $1.exe
You can add these in a script to make the process easier. Create a shell sript and add the parent directory to the PATH environment variable.
Example:
export PATH=$PATH":$HOME/Desktop/customcommands"
And also give execute permission to the script file.
Shell script:
#!/bin/sh
dpkg -s mono-complete > /dev/null
if [ $? -eq 0 ]; then
echo
else
read -p "Package mono-complete not installed. Press y to install or n to quit." response
yes="y"
if [ "$response" = "y" ];
then
sudo apt install mono-complete
echo " "
echo " "
fi
fi
mcs -out:$1.exe $1.cs
mono $1.exe

Categories