Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Embedding C# code


In this recipe, we will embed and execute C# code in our PowerShell script.

How to do it...

Let's explore how to embed C# code in PowerShell:

  1. Open PowerShell ISE as an administrator.

  2. Add the following script and run it:

    #define code
    #note this can also come from a file
    
    $code = @"
    using System;
    public class HelloWorld
    {
       public static string SayHello(string name)
       {
          return (String.Format("Hello there {0}", name));
       }
       public string GetLuckyNumber(string name)
       {
          Random random = new Random();
          int randomNumber = random.Next(0, 100);
          string message = String.Format("{0}, your lucky" +
                           " number for today is {1}", 
                           name, randomNumber);
          return message;
       }
    }
    "@
    
    #add this code to current session
    Add-Type -TypeDefinition $code
    
    #call static method
    [HelloWorld]::SayHello("belle")
    
    #create instance
    $instance = New-Object HelloWorld
    
    #call instance method
    $instance.GetLuckyNumber("belle")

How it works...