lecture 13, 14 & 15 c# cmd let programming and scripting

38
Lectures 15 - 17: C#, cmdLet programming & scripting Network design & Administration

Upload: wil-ferraciolli

Post on 19-May-2015

822 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 13, 14 & 15   c# cmd let programming and scripting

Lectures 15 - 17: C#, cmdLet programming & scriptingNetwork design & Administration

Page 2: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Why does a Systems Administrator need to know about programming?

• Tools not available to perform task• Have to write new tools

• Use scripting to provide more power than executing single command line tools

• Automate tasks• Need to alter the OS (if Unix based)• There are lots of reasons why a knowledge

of programming is essential! 2

Page 3: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Powershell

• Powershell is “the next generation command shell and scripting language”[1]

• Provides access to lots of powershell programs (cmdlets)• Cmdlets can be joined together (output -> input)• Powershell provides a set of scripting commands to

facilitate in linking cmdlets together (more later)• Can program your own cmdlets to do specific tasks

3

Page 4: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

What do you need to know to be able to program a cmdlet?• C# !• C# is a C++/Java like language• C# requires the .Net framework to be installed• Cmdlets are written in C# but you need to:

• Extend the PSCmdLet class• Provide parameter attributes• Implement the following methods:

• BeginProcessing• ProcessRecord• EndProcessing

• Provide your code!• Before we look at cmdlet programming in more detail, a quick

introduction to C# is in order!4

[4]

Page 5: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

C# Data types• C# has the same primitive data types that you find in C++ and

Java• int e.g. int value = 5;• bool e.g. bool receivedInput = false;• float e.g. float value = 8.5;• arrays e.g. string []params; BUT!

• More complex data types:• String• List• ArrayList• Stack• Queue• …

5

Page 6: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

C# Classes• In C#, everything is an Object• A class provides the blueprint as to what data and operations

it can offer• However, you have to use the class blueprint to create an

object instance before you can access it• Follows a similar syntax to a Java Class.

6

 

public class MyFirstClass { public MyFirstClass() { // Constructor … }}

MyFirstClass m = new MyFirstClass();m.print();

Use the new keyword to instantiate object

Use dot notation to access the objects methods

Page 7: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

using System; namespace ConsoleApplication1{ class MyFirstProgram { private String _message = "Hello ";

public MyFirstProgram(String userName) { Console.WriteLine(_message + userName); }  public static void Main(String[] args) { MyFirstProgram myProg = new MyFirstProgram("Clark"); } }}

Anatomy of a C# Program1. Using (import other

classes)2. Namespace3. Class definition4. Private data5. Class constructor6. One Main method

per program (has to be static)

7. Parameter passing8. Instantiating a new

object9. Writing output to

the console7

Page 8: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

C# Strings• Strings are objects of the System.String Class• Can assign a sequence of characters to them…

• i.e. use the assignment operator =• You can join strings together…

• Using the + operator• Because String is a class there are several handy methods and

properties it provides…• Length – returns the number of characters in the string• Substring( int startPosition, int length) – returns characters

between start and start+length characters 8

String machineName = "CIB108-34";

String fullName = machineName + ".ads.ntu.ac.uk";

Page 9: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

public class Employee{ private String name = string.Empty; 

public Employee(String n) { name = n; } 

public void print() { Console.WriteLine("Employee name: " + name ); } 

}

Inheritance• C# allows you to inherit functionality from another class.

9

public class Manager : Employee{ private List<Employee> employeeList = new List<Employee>(); 

public Manager(String name) : base(name) { } 

public void manages(Employee employee) { employeeList.Add(employee); }} 

Inherits the print() method

Page 10: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

The Object Class• When you create a new class (for example):

• You can define a class and not provide any explicit inheritance.• However, all classes derive from a base class even if it is not explicitly

stated.• This is the object class.

10

using System; public class MyFirstClass{ public MyFirstClass() { // … }}

Page 11: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

• Because all classes derive from object within C# we can use the object class as a way of providing a generic interface to methods

• This is done by boxing and unboxing which also allows value types (primitive data types) to act like reference types (objects)

• For example, boxing value types:

• However, unboxing must be explicit!

int myValue = 1000;object obj = myValue;int newValue = (int)obj;

The object class

1000myValue

int

obj

newValue10001000

11

public void add(object obj) { }

Page 12: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Namespaces• C# provides you with hundreds of classes that you can use

within your programs.• Each class you create/use will have a name (e.g.):

• What happens if there is another class called ListCommand?• You can use a Namespace to limit the scope of any classes that

you define:

• Now ListCommand is visible within the myLibrary namespace• You can now access your class as:

12

namespace myLibrary{ public class ListCommand { // ... }}

public class ListCommand

myLibrary.ListCommand ...

Page 13: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Interfaces• An interface allows you to define a specific interface to a class.• Any class that implements that interface will have to provide a

set of pre-defined method signatures.

13

namespace myLibrary{ interface MyListInterface { void add(object onj); object get(int index); int size(); void toString(); }}

Page 14: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Interfaces• To use an interface you have to specify a class which inherits

the interface

14

namespace myLibrary{ interface MyListInterface { void add(object onj); object get(int index); int size(); void toString(); }  public class MyList : MyListInterface { public MyList() { } }}

Page 15: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

this and is keywords• this

• Refers to current instance of an object• Example:

• is• provides you with a way to determine if the object supports an interface• If it does, then you can access methods within it

• Syntax:<expression> is <type>

• Example:

15

private string name; 

public void setName(string name) { this.name = name;}

Employee CKent = new Employee("Clark Kent");if( CKent is Employee ) CKent.print();

Page 16: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

C# Control Structures• C# provides the same control structures as C/C++ and Java

• if statement

• Remember - when comparing objects

• Isn’t comparing that the two objects contain the same data but is instead comparing the pointers of each object.

• But Strings are different!

16

if( x == 10 ) { // …} else { // ..}

if( obj1 == obj2 ) {}

String name1 = "clark";String name2 = "lois";if( name1 == name2 ) Console.WriteLine("they are the same!"); else Console.WriteLine("they are not the same!");

Page 17: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

C# Control Structures• C# provides the same control structures as C/C++ and Java

• Switch statement

17

switch( value ) {case 1:

Console.WriteLine("Option 1!");break;

case 2: Console.WriteLine("Option 2!");break;

default:Console.WriteLine("Option 2!");break;

}

Page 18: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

List<string> myList = new List<string>();for (int counter = 0; counter < 10; counter++) { myList.Add("item " + counter);}foreach (string value in myList) { Console.WriteLine(value);}

Loops• For loops are the same as in C++/Java

• Foreach:

18

for (int iCounter = 0; iCounter < 10; iCounter++){

Console.WriteLine("counter = " + iCounter);}

Page 19: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

namespace ConsoleApplication1{ class Program { static void Main(string[] args) { Console.WriteLine("Enter first number:"); int value1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter second number:"); int value2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("multiplying {0} by {1} gives {2}", value1, value2, (value1 * value2)); } }} 

Reading and Writing to the console

19

Page 20: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

• C# provides you with throw and try-catch statements so that you can handle any unwanted exceptions

• Classes that you use within your C# code will usually throw an exception if an error occurs (especially if you are relying on 3rd part api’s / libraries)

class Program { public List<string> myList = new List<string>(); 

static void Main(string[] args) { Program m = new Program(); for (int counter = 0; counter < 10; counter++) { m.myList.Add("item " + counter); } Console.WriteLine(m.getIndex(50)); } 

public string getIndex(int index){ if (index > myList.Count) throw new IndexOutOfRangeException(); else return myList[index]; }}

Exception handling

20

Page 21: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

class Program { public List<string> myList = new List<string>(); 

static void Main(string[] args) { Program m = new Program(); for (int counter = 0; counter < 10; counter++) { m.myList.Add("item " + counter); } Try { Console.WriteLine(m.getIndex(50)); } catch (IndexOutOfRangeException error) { Console.WriteLine("Error occurred: " + error.Message); } } 

public string getIndex(int index) { if (index > myList.Count) throw new IndexOutOfRangeException(); else return myList[index]; }} 

Exception handling

21

Page 22: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Properties• In C# you can use properties to access private data• Use the get and set methods to allow read or write access

22

private string _name; public string Name{ get { return _name; } set { _name = value; }}

The property!

Private data stored within the class

The get method returns the value of the private data element. Used when access the property by name or on RHS of =

The set method allows you to assign a value to the private data element. This is called automatically when = is used

Special keyword in C#. Gives the value from the RHS of an = operation.

Examples:Name = “Clark”;String userName = Name;

Page 23: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Exercise!

• Spend 5 minutes to work out what errors are in the code in the hand-out.

• The person who identifies the correct number of errors gets a prize!

23

Page 24: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Now back to cmdlets … Cmdlet naming[2]

• Cmdlets are named using a verb-noun pair• Verbs are used to describe what action the cmdlet will perform• Nouns are used to describe what entity the cmdlet will perform the

action on• Examples (encountered in the labs):

• New-ADComputer• Get-Help• Set-ADUser

• There are lots of pre-defined verbs (stored in classes):• VerbsCommon VerbsLifeCycle• VerbsCommunications VerbsSecurity• VerbsData VerbsOther• VerbsDiagnostic 24

Page 25: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Sending input to cmdlets• Cmdlets can accept parameters

• Cmdlets can also be chained together so that the output of one can be the input to another.

• For example:

• Here, new-gpo is creating a new GPO object and passing it (using the pipe symbol |) to the new-gplink cmdlet.

25

new-gpo –name “Publishers Policy” | new-gplink –target “ou=publishers, dc=testnetwork, dc=com”

new-gpo –name “Publishers Policy”

Page 26: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Anatomy of a cmdlet

26

using System;using System.Collections.Generic;using System.Text;using System.Management.Automation; 

namespace HelloWorldExample { [Cmdlet(VerbsCommunications.Send, "Hello World Example!")] public class HellowWorld : PSCmdlet { [Parameter(Mandatory = true)] public string yourName { get { return userName; } set { userName = value; } } private string userName; 

protected override void ProcessRecord() { WriteObject("Hello" + userName + "!"); } }}

Page 27: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Processing within cmdlets• The Cmdlet and PSCmdlet classes provide the following methods:

• BeginProcessing• ProcessRecord• EndProcessing

• These methods need to be implemented by the developer• Sending objects through a pipeline between cmdlets can be

demonstrated by the following :-

27

Object 1

Object 2

Object 3New Output

Object

Begin Processing

Process Record

End Processing

cmdlet

New Output Object 2

New Output Object 3

Input Pipeline Output Pipeline

Page 28: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Snap-ins

• Once you have finished writing your C# cmdlet you have to create another file which contains snap-in information.

• Snap-ins are used to register cmdlets with powershell and to setup any registry entries

• If you do not register a cmdlet within powershell you will not be able to run it

• A snap-in for the cmdlet would be added to your project and get linked in when the project is compiled 28

Page 29: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Anatomy of a Snap-in

29

using System;using System.Collections.Generic;using System.Text;using System.Management.Automation;using System.ComponentModel; 

namespace ListCommand { [RunInstaller(true)] public class ListCommandSnapIn : PSSnapIn { public override string Name { get { return "ListCommand"; } } public override string Vendor { get { return "Jon Robinson"; } } public override string Description { get { return "New directory listing command"; } } }}

Page 30: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Compiling cmdlets and linking into Powershell1. Cmdlets can be created and compiled within visual

studio• Need a special template project to create cmdlets

which can be downloaded from the web[3]

2. Can also be compiled using the .Net framework C# compiler (csc.exe)

• Found under windows\system32\Microsoft.Net\<.net version>

3. Use the installutil command to register the cmdlet in powershell

4. Use add-pssnapin <new cmdlet> to access cmdlet from powershell prompt

30

Page 31: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Powershell Scripting

• Powershell provides a rich scripting language• Used to provide more complex functionality

linking cmdlet’s together• Types of language features available:

• variables• if/else statements• switch statements• for loops• command line parameter passing• Etc…

31

Page 32: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Powershell scripting example [1]

32

[int]$intPing=10[string]$intNetwork="127.0.0." for($i=1; $i -le $intPing; $i++) { $strQuery = "select * from win32_pingstatus where address = '" + $intNetwork + $i + "'" $wmi = get-wmiobject -query $strQuery "Pinging $intNetwork$i ..." if( $wmi.statuscode -eq 0 ) {"success"} else {"error: " + $wmi.statuscode + " occurred"}}

-eq (equal to)-lt (less than) -gt (greater than) -ge (greater than or equal to)-le (less than or equal to)-ne (not equal)

Variables have the following syntax:

[<data type>] $<variable name> = <data value>

Available data types:[array] [bool][byte] [char][decimal] [double][hashtable] [int][long] [string][single] [xml]

If statement syntax: if( $<variable name> <evaluation expression> <value> ) {"success"} else {"fail"}

Page 33: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Powershell switch example

33

[int] $simpleSwitchExample = 2 switch($simpleSwitchExample) { 1 { "Option 1" } 2 { "Option 2" } 3 { "Option 3" } default { "No idea..." }}

Switch statement syntax:

switch <expression evaluation type> ($<variable name>) {… expressions …}

Page 34: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Powershell switch example

34

[string] $regularExpressionSwitchExample = "1234"[int] $size = 0

switch -regex ($regularExpressionSwitchExample) { "\d{4}" { $size = 4; break; } "\d{3}" { $size = 3; break; } "\d{2}" { $size = 2; break; } "\d{1}" { $size = 1; break; } default { "No idea..." $size = -1 }}

if( $size -gt 0 ) { "The string had " + $size + " characters" }else { "Wasn't able to work out how many characters!" }

-regex (regular expression)-wildcard (wildcard!)

Page 35: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Getting input from the user• Scripts can interact with the user to provide more functionality.• Scripts can display information by just saying “message…”.

• However, this is not formatted.• Can use the Write-Host cmdlet to display output.

• Can format the message (colours, spaces, etc)• For example:

Write-host “hello world” –foregroundcolor black –backgroundcolor white

• Scripts can get input from the user by using the Read-Host cmdlet.• For example:

$ipAddress = Read-Host “Enter the ip address:”• Can use the –AsSecureString option to mask what has been entered.

$password = read-host –assecurestring “Enter your password:” 35

Page 36: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Powershell functions

36

function display {param ([string]$message="")Write-Host "Your message is $message"

} display "hello world"

function display( $message ) {Write-Host "Your message is $message"

} display "hello world"

Un-typed – could be any type of information

Page 37: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Powershell functions

37

function display { param ([string]$message="") param ([int]$repeat=1) $returnMessage = “” for($count=1; $count –le $repeat; $count++) { Write-Host "Your message is $message“

$returnMessage = $returnMessage + “Your message is $message”

} return $returnMessage} display("hello world“, 5)

Page 38: Lecture 13, 14 & 15   c# cmd let programming and scripting

Net

wor

k D

esig

n &

Adm

inist

ratio

n

Next Time & References• Updating Systems

References[1] “Windows PowerShell Scripting Guide”, Wilson, E., Microsoft Press[2] http://msdn.microsoft.com/en-us/library/windows/desktop/ms714428%28v=vs.85%29.aspx[3] http://channel9.msdn.com/forums/sandbox/249904-Windows-PowerShell-Visual-Studio-2005-Templates-C-and-VBNET[4] http://msdn.microsoft.com/en-us/library/zw4w595w.aspx

38