C# Powershell Tutorial – Complete Guide

Welcome to an exciting tutorial on a popular topic for many of our coding pupils out there – C# in PowerShell. If you’re curious about creating simple but powerful scripts using C# or wanting to take your game creation skills to the next level, then you’re at the right place!

What is C# in PowerShell?

C# in PowerShell refers to the practice of using C#, one of the most popular programming languages around, within the PowerShell environment. PowerShell is a cross-platform task automation solution, comprised of a command-line shell, a scripting language, and a configuration management framework. By utilizing C# within this setup, you can achieve effective and easily automated tasks.

What is it used for?

Combining C# with PowerShell scriptwriting can provide a significant advantage in game development, as well as in tasks requiring automation or complex batch operations across various platforms. The unique benefits of both tools are harnessed to speed-up development processes and create more efficient scripts and applications.

Why should you learn it?

Learning to use C# in PowerShell offers an excellent opportunity to expand your coding repertoire and create more efficient workflows for game development and other applications. This knowledge provides you with a competitive edge in the industry and can be a valuable asset to potential employers. Plus, it’s a fun and satisfying talent to master. So why wait? Let’s dive in!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Writing Basic C# Scripts within PowerShell

To begin with, we will be covering some basic examples of employing C# code within PowerShell to execute simple tasks.

#Creating a HelloWorld Example
Add-Type -TypeDefinition @"
public class HelloWorld{
    public static void SayHello(){
        System.Console.WriteLine("Hello, World!");
    }   
}"@
[HelloWorld]::SayHello()

This code will create a simple C# class, HelloWorld, using the Add-Type cmdlet within PowerShell. The SayHello method within the class simply outputs “Hello, World!” when called. The last line of the script calls this method, executing it within the PowerShell environment.

Performing Mathematical Operations

Let’s delve deeper by writing C# code that conducts mathematical operations in PowerShell.

#Multiply Function
Add-Type -TypeDefinition @"
public class Multiply{
    public static int DoMultiply(int a, int b){
        return a * b;
    }
}"@
[Multiply]::DoMultiply(5,7)

This script creates a class called Multiply containing a method DoMultiply that takes two integers and returns their product. The method is then called with the values 5 and 7, so the output will be 35.

Using Predefined C# Libraries in PowerShell

C# provides numerous libraries that can be used within PowerShell to conduct a variety of operations. Let’s consider one example with the System.IO library to work with files.

#Carrying Out File Operations
Add-Type -TypeDefinition @"
using System.IO;
public class FileOp{
    public static void WriteToFile(string path, string content){
        File.WriteAllText(path, content);
    }
}"@
[FileOp]::WriteToFile("C:\\temp\\sample.txt", "Hello from Zenva!")

This script introduces the use of C# libraries with PowerShell. The class FileOp has a method WriteToFile that takes a file path and a string, and writes the string to the file at the given path. In this example, “Hello from Zenva!” will be written to the file located at “C:\\temp\\sample.txt”.

Creating Objects in C# for use in PowerShell

It’s also possible to create objects in C# and then use them within PowerShell. Here’s how:

#Creating a Student Object

Add-Type -TypeDefinition @"
public class Student{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Student(string name, int age){
        this.Name = name;
        this.Age = age;
    }
}"@

$student1 = New-Object Student("Zenva Student", 21)
$student1.Name
$student1.Age

This code creates a simple C# Student class with Name and Age properties and a constructor. The constructor is used to create a new Student object within PowerShell and accessing the object’s properties displays the values respectively.

Advanced Concepts in Using C# with PowerShell

Once you’ve mastered the basics, it’s time to peek at some more advanced concepts. With the following examples, you’ll see the true power of combining C# with PowerShell.

Exception Handling in C# Scripts within PowerShell

Exception handling is a crucial factor in any programming language, and C# is not an exception. It becomes easier in PowerShell when using C#.

#C# Exception Handling
Add-Type -TypeDefinition @"
public class Div{
    public static int Divide(int a, int b){
        try {
            return a / b;
        }
        catch (System.DivideByZeroException){
            System.Console.WriteLine("Cannot divide by zero!!!");
            return 0;
        }
    }
}"@
[Div]::Divide(5,0)

In this script, a Divide method is defined within the Div class that performs division. Here, a DivideByZeroException is caught to handle cases where b equals zero.

Working with Data Structures

Data structures play a vital role in effective programming, especially in game development. With the following code snippet, you will see how we can use a Hashtable data structure in PowerShell with C#.

#HashTables in C#
Add-Type -TypeDefinition @"
using System.Collections;

public class HashTableOp{
    public static Hashtable CreateHashTable(){
        Hashtable ht = new Hashtable();
        ht.Add("1", "One");
        ht.Add("2", "Two");
        ht.Add("3", "Three");
        return ht;
    }
}"@

$hashTable = [HashTableOp]::CreateHashTable()
$hashTable["2"]

This script creates a Hashtable using C# and returns it to PowerShell. The hashtable value corresponding to key “2” is then accessed within PowerShell, which would return “Two”.

Working with Files & Directories

PowerShell is widely used for automated tasks, including file and directory operations. Here is an example where we create a directory in PowerShell using C#.

#Create Directory Using C#

Add-Type -TypeDefinition @"
using System.IO;

public class DirOp{
    public static void CreateDirectory(string dirPath){
        if (!Directory.Exists(dirPath)){
            Directory.CreateDirectory(dirPath);
        }
    }
}"@

[DirOp]::CreateDirectory("C:\\temp\\new_directory")

This script demonstrates C# and PowerShell working together to check if a directory exists at a given path, and if it doesn’t, a new directory is created at that location.

Working with Databases

We can also interact with databases using C#. Here, we’ll take a look at a basic example where a database connection is established using C# within PowerShell.

#DB Connection with C# (Example with SQL Server)

Add-Type -TypeDefinition @"
using System.Data.SqlClient;

public class DBConn{
    public static SqlConnection GetSqlConnection(string connectionString){
        SqlConnection conn = new SqlConnection(connectionString);
        conn.Open();
        return conn;
    }
}"@

$conn = [DBConn]::GetSqlConnection("Your_Connection_String")

This script establishes an SQL Server connection using C# within PowerShell. The SQL connection string needs to be replaced with your actual connection string. Remember that using real DB connections should be handled with care and always securely.

Interacting with APIs

APIs allow systems to communicate with one another. C# can be used within PowerShell for seamless API interaction, including making HTTP requests and interpreting responses.

#HTTP Request using C# 
Add-Type -TypeDefinition @"
using System.Net;

public class API{
    public static void MakeRequest(string url){
        WebClient client = new WebClient();
        string response = client.DownloadString(url);
        System.Console.WriteLine(response);
    }
}"@
[API]::MakeRequest("http://your_api_url")

This script uses C# to make an HTTP request to a given URL and print the server’s response. Don’t forget to replace http://your_api_url with the actual URL of the API endpoint you want to get the response from.

Working with JSON Data

In modern programming, JSON data is incredibly common. Let’s look at how C# can parse JSON data within PowerShell.

#Parsing JSON using C#
Add-Type -TypeDefinition @"
using System.Collections.Generic;
using System.Web.Script.Serialization;

public class JSONParser{
    public static Dictionary<string, object> ParseJSON(string jsonString){
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Deserialize<Dictionary<string, object>>(jsonString);
    }
}"@
$dict = [JSONParser]::ParseJSON('{"name": "Zenva", "courses": 100}')
$dict["courses"]

This script uses the JavaScriptSerializer class in C# to convert a JSON string into a PowerShell dictionary object, allowing you to access the data directly within your PowerShell scripts.

Working with XML Data

Similar to JSON, XML is abundantly used for storing and transferring data. With the power of C#, we can parse XML data in PowerShell.

#Parse XML using C#
Add-Type -TypeDefinition @"
using System.Xml;

public class XMLParser{
    public static XmlDocument ParseXML(string xmlString){
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlString);
        return doc;
    }
}"@
$doc = [XMLParser]::ParseXML('Zenva100')
$doc.SelectSingleNode("//courses").InnerText

With this script, you can parse an XML string and create an XML document object in PowerShell. This allows you to perform operations like extracting XML node values (as shown above), adding new nodes or modifying existing ones.

Performing Operations on Date and Time

The DateTime class in C# is widely used for manipulations involving date and time. Here’s how it’s done:

#Using DateTime in C#
Add-Type -TypeDefinition @"
using System;

public class DateTimeOp{
    public static string GetLongDate(){
        return DateTime.Now.ToLongDateString();
    }
}"@
[DateTimeOp]::GetLongDate()

This script uses C# to get the current date in a long date string format within PowerShell.

Summary

Now that you’ve seen the range of powers bestowed upon you by using C# within PowerShell, the next step is to dig deeper and start using these concepts in your game creation or other projects. Also, don’t hesitate to explore even more applications of C# within PowerShell that we didn’t cover here.

At Zenva, we pride ourselves on offering a blended learning ecosystem with first-rate, project-based courses, teaching a wide range of programming niches and skills. Through our tried-and-true teaching methods, we help students become industry-ready developers with a portfolio of projects, primed to impress potential employers or enter thriving freelance markets.

Where to Go Next

Now that you’ve dipped your toes into the world of integrating C# with PowerShell, it’s crucial to sustain the momentum and keep enhancing these newfound skills. We’re excited to extend the journey with you, unlocking more beneficial aspects of programming and game development.

At Zenva, you can continue your learning path with our Unity Game Development Mini-Degree.

This mini-degree program will guide you through the realms of game development using Unity, offering interactive lessons, live coding sessions, and quizzes to solidify your understanding alongside building a portfolio of Unity games and projects. You’ll learn to create a variety of games in 2D, 3D, AR, and VR. With high-demand in the industry for Unity skills, this is a perfect opportunity to boost your career. If you’re looking for more Unity-related content, check out our broader collection of Unity courses.

Remember, whether you’re starting off or already have a firm grasp of the basics, Zenva is here to support you from beginner to professional!

Conclusion

There’s an undeniable beauty in the intricate dance between C# and PowerShell, a combination that many top-tier developers have learned to master. Through this tutorial, we’ve embarked on a thrilling exploration of the crossroads where a robust programming language meets a real-world, automated task handler. But remember – this is just the start!

Whether you are excited to get started in game development, eager to enhance your programming skills, or looking to build a robust portfolio, your journey has just begun. With Zenva’s Unity Game Development Mini-Degree, we invite you to tread the exciting path of learning by doing. Learn, practice, innovate, create – the power of programming is at your fingertips with Zenva!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.