Lectures 15 - 17:C#, cmdLetprogramming &scriptingNetwork design & Administration
Why does a Systems Administratorneed to know about programming?• Tools not available to perform task • Have to write new t...
Powershell• Powershell is “the next generation command shell and  scripting language”[1]• Provides access to lots of power...
What do you need to know tobe able to program a cmdlet?• C# !• C# is a C++/Java like language• C# requires the .Net framew...
C# Data types• C# has the same primitive data types that you find in C++ and  Java  •   int         e.g. int value = 5;  •...
C# Classes• In C#, everything is an Object• A class provides the blueprint as to what data and operations  it can offer• H...
Anatomy of a C# Programusing System;                                                     1.   Using (import othernamespace...
C# Strings• Strings are objects of the System.String Class• Can assign a sequence of characters to them…    String machine...
Inheritance    • C# allows you to inherit functionality from another class.public class Employee{    private String name =...
The Object Class• When you create a new class (for example):                using System;                public class MyFi...
The object class• Because all classes derive from object within C# we can use the  object class as a way of providing a ge...
Namespaces• C# provides you with hundreds of classes that you can use within  your programs.• Each class you create/use wi...
Interfaces• An interface allows you to define a specific interface to a class.• Any class that implements that interface w...
Interfaces• To use an interface you have to specify a class which inherits  the interface    namespace myLibrary    {     ...
this and is keywords• this   • Refers to current instance of an object   • Example:         private string name;         p...
C# Control Structures• C# provides the same control structures as C/C++ and Java• if statement       if( x == 10 ) {      ...
C# Control Structures• C# provides the same control structures as C/C++ and Java• Switch statement  switch( value ) {     ...
Loops• For loops are the same as in C++/Java  for (int iCounter = 0; iCounter < 10; iCounter++)  {     Console.WriteLine("...
Reading and Writing to the  consolenamespace ConsoleApplication1{  class Program  {    static void Main(string[] args)    ...
Exception handling    • C# provides you with throw and try-catch statements so that      you can handle any unwanted excep...
Exception handlingclass Program {    public List<string> myList = new List<string>();    static void Main(string[] args) {...
Properties     • In C# you can use properties to access private data     • Use the get and set methods to allow read or wr...
Exercise!• Spend 5 minutes to work out what  errors are in the code in the hand-out.• The person who identifies the correc...
Now back to cmdlets … Cmdlet naming[2]• Cmdlets are named using a verb-noun pair• Verbs are used to describe what action t...
Sending input to cmdlets• Cmdlets can accept parameters            new-gpo –name “Publishers Policy”• Cmdlets can also be ...
Anatomy of a cmdletusing    System;using    System.Collections.Generic;using    System.Text;using    System.Management.Aut...
Processing within cmdlets  • The Cmdlet and PSCmdlet classes provide the following methods:             • BeginProcessing ...
Snap-ins• Once you have finished writing your C# cmdlet  you have to create another file which contains  snap-in informati...
Anatomy of a Snap-inusing   System;using   System.Collections.Generic;using   System.Text;using   System.Management.Automa...
Compiling cmdlets and linkinginto Powershell1. Cmdlets can be created and compiled within visual   studio  • Need a specia...
Powershell Scripting• Powershell provides a rich scripting language• Used to provide more complex functionality  linking c...
Powershell scripting example [1][int]$intPing=10[string]$intNetwork="127.0.0."       Variables have the following syntax: ...
Powershell switch example   Switch statement syntax:   switch <expression evaluation type> ($<variable name>) {   … expres...
Powershell switch example[string] $regularExpressionSwitchExample = "1234"[int] $size = 0switch -regex ($regularExpression...
Getting input from the user• Scripts can interact with the user to provide more  functionality.• Scripts can display infor...
Powershell functionsfunction display {      param ([string]$message="")      Write-Host "Your message is $message"}       ...
Powershell functionsfunction display {  param ([string]$message="")  param ([int]$repeat=1)  $returnMessage = “”  for($cou...
Next Time & References• Updating SystemsReferences[1] “Windows PowerShell Scripting Guide”, Wilson, E., Microsoft Press[2]...
Upcoming SlideShare
Loading in …5
×

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

1,365 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,365
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
14
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

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

  1. 1. Lectures 15 - 17:C#, cmdLetprogramming &scriptingNetwork design & Administration
  2. 2. Why does a Systems Administratorneed to know about programming?• Tools not available to perform task • Have to write new tools• Use scripting to provide more power than Network Design & Administration 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
  3. 3. 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) Network Design & Administration• 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
  4. 4. What do you need to know tobe 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 Network Design & Administration • Provide parameter attributes • Implement the following methods: • BeginProcessing • ProcessRecord • EndProcessing • Provide your code!• Before we look at cmdlet programming in more detail, a quick 4 introduction to C# is in order! [4]
  5. 5. 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; Network Design & Administration • arrays e.g. string []params; BUT!• More complex data types: • String • List • ArrayList • Stack • Queue 5 • …
  6. 6. 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 Network Design & Administration object instance before you can access it• Follows a similar syntax to a Java Class. public class MyFirstClass{ public MyFirstClass() { // Constructor … } Use dot notation tonew keyword Use the access the objects to instantiate object } methods 6 MyFirstClass m = new MyFirstClass(); m.print();
  7. 7. Anatomy of a C# Programusing System; 1. Using (import othernamespace ConsoleApplication1 classes){ 2. Namespace class MyFirstProgram 3. Class definition { private String _message = "Hello "; 4. Private data 5. Class constructor Network Design & Administration public MyFirstProgram(String userName) 6. One Main method { per program (has to Console.WriteLine(_message + userName); } be static) 7. Parameter passing public static void Main(String[] args) 8. Instantiating a new { object MyFirstProgram myProg = new MyFirstProgram("Clark"); } 9. Writing output to } the console} 7
  8. 8. C# Strings• Strings are objects of the System.String Class• Can assign a sequence of characters to them… String machineName = "CIB108-34"; • i.e. use the assignment operator = Network Design & Administration• You can join strings together… String fullName = machineName + ".ads.ntu.ac.uk"; • 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
  9. 9. Inheritance • C# allows you to inherit functionality from another class.public class Employee{ private String name = string.Empty; public Employee(String n) Network Design & Administration { public class Manager : Employee name = n; Inherits the print() method {} private List<Employee> employeeList = new List<Employee>(); public void print() { public Manager(String name) : base(name) Console.WriteLine("Employee name: " + name ); { } }} public void manages(Employee employee) { employeeList.Add(employee); 9 } }
  10. 10. The Object Class• When you create a new class (for example): using System; public class MyFirstClass Network Design & Administration { public MyFirstClass() { // … } }• You can define a class and not provide any explicit inheritance.• However, all classes derive from a base class even if it is not 10 explicitly stated.• This is the object class.
  11. 11. The object class• Because all classes derive from object within C# we can use the object class as a way of providing a generic interface to methods public void add(object obj) { }• This is done by boxing and unboxing which also allows value types (primitive data types) to act like reference types (objects) Network Design & Administration• For example, boxing value types: int myValue = 1000; object obj = myValue; int newValue = (int)obj; obj myValue int newValue 1000 1000 1000 11• However, unboxing must be explicit!
  12. 12. 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.): public class ListCommand• What happens if there is another class called ListCommand? Network Design & Administration• You can use a Namespace to limit the scope of any classes that you define: namespace myLibrary { public class ListCommand { // ... } }• Now ListCommand is visible within the myLibrary namespace 12• You can now access your class as: myLibrary.ListCommand ...
  13. 13. 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. namespace myLibrary Network Design & Administration { interface MyListInterface { void add(object onj); object get(int index); int size(); void toString(); } } 13
  14. 14. Interfaces• To use an interface you have to specify a class which inherits the interface namespace myLibrary { interface MyListInterface Network Design & Administration { void add(object onj); object get(int index); int size(); void toString(); } public class MyList : MyListInterface { public MyList() { } 14 } }
  15. 15. this and is keywords• this • Refers to current instance of an object • Example: private string name; public void setName(string name) { Network Design & Administration this.name = name; }• 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 Employee CKent = new Employee("Clark Kent"); if( CKent is Employee ) CKent.print();
  16. 16. C# Control Structures• C# provides the same control structures as C/C++ and Java• if statement if( x == 10 ) { // … } else { // .. Network Design & Administration }• Remember - when comparing objects if( obj1 == obj2 ) {}• Isn’t comparing that the two objects contain the same data but is instead comparing the pointers of each object.• But Strings are different! String name1 = "clark"; String name2 = "lois"; 16 if( name1 == name2 ) Console.WriteLine("they are the same!"); else Console.WriteLine("they are not the same!");
  17. 17. C# Control Structures• C# provides the same control structures as C/C++ and Java• Switch statement switch( value ) { Network Design & Administration case 1: Console.WriteLine("Option 1!"); break; case 2: Console.WriteLine("Option 2!"); break; default: Console.WriteLine("Option 2!"); break; 17 }
  18. 18. Loops• For loops are the same as in C++/Java for (int iCounter = 0; iCounter < 10; iCounter++) { Console.WriteLine("counter = " + iCounter); } Network Design & Administration• Foreach: 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); 18 }
  19. 19. Reading and Writing to the consolenamespace ConsoleApplication1{ class Program { static void Main(string[] args) Network Design & Administration { 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)); } 19 }}
  20. 20. Exception handling • C# provides you with throw and try-catch statements so that you can handle any unwanted exceptions • Program {class Classes that you use within your C# code will usually throw an rd public List<string> myList =(especially if you are relying on 3 exception if an error occurs new List<string>(); static api’s / Main(string[] args) { part void libraries) Network Design & Administration 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]; 20 }}
  21. 21. Exception handlingclass 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); Network Design & Administration } 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]; 21 }}
  22. 22. Properties • In C# you can use properties to access private data • Use the get and set methods to allow read or write access Private data stored within the class Network Design & AdministrationThe get methodreturns the value of private string _name;the private data The property!element. Used whenaccess the property by public string Namename or on RHS of = { Special keyword in C#. get { return _name; } Gives the value from set { _name = value; } the RHS of an =The set method allows operation.you to assign a value }to the private data 22element. This is called Examples:automatically when = Name = “Clark”;is used String userName = Name;
  23. 23. Exercise!• Spend 5 minutes to work out what errors are in the code in the hand-out.• The person who identifies the correct Network Design & Administration number of errors gets a prize! 23
  24. 24. 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): Network Design & Administration • New-ADComputer • Get-Help • Set-ADUser• There are lots of pre-defined verbs (stored in classes): • VerbsCommon VerbsLifeCycle • VerbsCommunications VerbsSecurity • VerbsData VerbsOther 24 • VerbsDiagnostic
  25. 25. Sending input to cmdlets• Cmdlets can accept parameters new-gpo –name “Publishers Policy”• Cmdlets can also be chained together so that the output of one can be the input to another. Network Design & Administration• For example: new-gpo –name “Publishers Policy” | new-gplink –target “ou=publishers, dc=testnetwork, dc=com”• Here, new-gpo is creating a new GPO object and passing it (using the pipe symbol |) to the new-gplink cmdlet. 25
  26. 26. Anatomy of a cmdletusing System;using System.Collections.Generic;using System.Text;using System.Management.Automation;namespace HelloWorldExample { [Cmdlet(VerbsCommunications.Send, "Hello World Example!")] Network Design & Administration 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 + "!"); 26 } }}
  27. 27. Processing within cmdlets • The Cmdlet and PSCmdlet classes provide the following methods: • BeginProcessing • ProcessRecord • EndProcessing • These methods need to be implemented by the developer Network Design & Administration • Sending objects through a pipeline between cmdlets can be demonstrated by the following :-Input Pipeline Output PipelineObject 1 cmdletObject 2 Begin Process EndObject 3 Processing Record Processing 27 New Output Object 2 Object3
  28. 28. 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 Network Design & Administration 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 28 compiled
  29. 29. Anatomy of a Snap-inusing System;using System.Collections.Generic;using System.Text;using System.Management.Automation;using System.ComponentModel;namespace ListCommand { [RunInstaller(true)] Network Design & Administration 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"; } 29 } }}
  30. 30. Compiling cmdlets and linkinginto 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# Network Design & Administration compiler (csc.exe) • Found under windowssystem32Microsoft.Net<.net version>3. Use the installutil command to register the cmdlet in powershell4. Use add-pssnapin <new cmdlet> to access cmdlet from powershell prompt 30
  31. 31. Powershell Scripting• Powershell provides a rich scripting language• Used to provide more complex functionality linking cmdlet’s together• Types of language features available: Network Design & Administration • variables • if/else statements • switch statements • for loops • command line parameter passing 31 • Etc…
  32. 32. Powershell scripting example [1][int]$intPing=10[string]$intNetwork="127.0.0." Variables have the following syntax: [<data type>] $<variable name> = <data value>for($i=1; $i -le $intPing; $i++) { Available data types: $strQuery = "select * from win32_pingstatus Network Design & Administration [array] [bool]where address = " [char] [byte] + $intNetwork + $i + "" $wmi [decimal] = get-wmiobject -query $strQuery [double] [hashtable] [int] "Pinging $intNetwork$i ..." [long] [string] if( $wmi.statuscode -eq 0 ) [single] [xml] {"success"} -eq (equal to) else If statement syntax: -lt (less than) {"error: " + $wmi.statuscode + " occurred"} -gt (greater than) if( $<variable name> <evaluation expression> <value> )equal to) -ge (greater than or 32} {"success"} -le (less than or equal to) else -ne (not equal) {"fail"}
  33. 33. Powershell switch example Switch statement syntax: switch <expression evaluation type> ($<variable name>) { … expressions … } Network Design & Administration [int] $simpleSwitchExample = 2 switch($simpleSwitchExample) { 1 { "Option 1" } 2 { "Option 2" } 3 { "Option 3" } default { "No idea..." } 33 }
  34. 34. Powershell switch example[string] $regularExpressionSwitchExample = "1234"[int] $size = 0switch -regex ($regularExpressionSwitchExample) { "d{4}" { $size = 4; break; } "d{3}" { $size = (regular expression) -regex 3; break; } -wildcard (wildcard!) Network Design & Administration "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 { "Wasnt able to work out how many characters!" } 34
  35. 35. 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. Network Design & Administration • 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 35 entered. $password = read-host –assecurestring “Enter your password:”
  36. 36. Powershell functionsfunction display { param ([string]$message="") Write-Host "Your message is $message"} Network Design & Administrationdisplay "hello world" Un-typed – could be any type of informationfunction display( $message ) { Write-Host "Your message is $message"}display "hello world" 36
  37. 37. Powershell functionsfunction display { param ([string]$message="") param ([int]$repeat=1) $returnMessage = “” for($count=1; $count –le $repeat; $count++) { Network Design & Administration Write-Host "Your message is $message“ $returnMessage = $returnMessage + “Your message is $message” } return $returnMessage} 37display("hello world“, 5)
  38. 38. Next Time & References• Updating SystemsReferences[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 Network Design & Administration[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

×