Full Transcript

1901 Lecture One: Windows Scripting Overview Like JavaScript for HTML pages, Windows supports various ways (languages) of scripting the operating system – Batch, PowerShell, VBScript, and JScript. All of these languages use text files for their source code and all do the same job – automate tasks th...

1901 Lecture One: Windows Scripting Overview Like JavaScript for HTML pages, Windows supports various ways (languages) of scripting the operating system – Batch, PowerShell, VBScript, and JScript. All of these languages use text files for their source code and all do the same job – automate tasks that need to be done at the operating system level. They are commonly used in networking to automate things like adding users and/or groups, maintenance of log files, and deployment of applications across multiple computers. Some scripting languages offer more features (power) than others, but all offer the following basics:     Creating and using variables Input from the user and output to the user Use of control structures like if, switch, for, and while Support for functions and arrays Batch File Scripting          Text files ending in either.bat or.cmd – use of the cmd extension is now preferred over the older bat extension. o Create a text based file in your favorite text editor – notepad, notepad++, sublime, … – and save the files with a cmd extension Batch files run in the command prompt window (cmd.exe) o To open a command window: type cmd in the search window and press enter o To open a command window with administrative priveleges: type cmd in the search window and right-click on the result (Command Prompt – desktop app) and select run as administrator Like Windows, batch file code is not case sensitive Can include basic Windows/DOS commands like dir, cd, rm, rmdir, mkdir, copy, move, … into your source code. o Anything you can do at the command line can be a line of code in your batch file including file redirection (using , and >>) and piping (using |) Line comments start with the keyword rem o could use two colons (::) for comments but this can cause issues with some logic o there are no block comments in batch files The echo command is used for output to the user: echo “Hello World” would display Hello World to the user o @echo off is commonly the first line in a batch file – by default, a batch file will display its command as it runs so echo off turns off this display for the whole script. The @ sign in front makes the command apply to itself as well – which is about the only time you will use the @ sign. The start command is used to run programs (or files associate with programs): o start mspaint.exe with open Microsoft’s Paint program. o start www.dogpile.com will open the DogPile search engine page in your default web browser. o start help.txt will open the help.txt file (provided it exists and is in the same directory as the batch file) in your default text editor. The pause command causes the batch file to pause until a standard key (like the spacebar) is pressed. o The pause command results in the output: Press any key to continue… o If you don’t want the pause output displayed: pause > nul (redirect the output of the pause command to the pseudo-variable called nul). Input from the user comes from the command line…at the same time the batch file is executed (as command line arguments)... o      If your batch file was called testit.cmd: testit peter dave marsha will result in the testit.cmd file being executed with the argument peter being represented by the variable %1, dave being represented by the variable %2, marsha being represented by the variable %3, and the command itself (testit) represented by the variable %0. So if your batch file had the line echo %1, the output would be peter. The set command is used to declare variables: o For string variables: set myString=Hello World will assign the string Hello World to myVariable. Note that there are no spaces before or after the assignment operator. o For numerical variables: set /A myNumber=3 – here the only difference is the /A to indicate a numerical variable. To use the value of a variable, the variable name has to enclosed in % signs. o To output the value of a variable to the user: echo %myVariable% o To use the value in a calculation: set /A result=%num1% + %num2% Using if and if-else for selection/determination logic: o General Form: if condition (true statements) else (false statements) o Condition for strings: use two equal (==) signs for equality comparisons o Condition for numbers: equ (equal), neq (not equal), lss (less than), leq (less than or equal to), gtr (greater than), geq (greater than or equal to) o Use if not for checking a false condition: if not condition (false statements) else (true statements) o Use if exist for checking if a file or folder exists: if exist file/folder (true statements) else (false statements) o Use if defined for checking if a variable exist: if defined variableName (true statements) else (false statements) o Note: Use quotation marks around both operands (sides) of an if – can help with errors if the variable doesn’t exist. o Note: When combining an else statement with parenthesis, always put the parenthesis on the same line as else since cmd.exe does a rather primitive one-line-at-a-time parsing of the command. You can simulate a function by using a label and the call command (the goto command can also be used but the call command is preferred): o First, declare your function by creating a label – a label is a word preceded by a colon. The should be done after your main code body – your functions have to come last. o The body of the function contains any of the above logic and commands o The last line of a function is usually exit /B 0 – which exits the script with an error code of zero (meaning that everything went well). Note that functions don’t return to the line of code they are called from. o To call a function, use the call keyword followed by the label name (including the colon). You can also pass values to a function by including either the literal value(s) or the variable name(s). The values passed go into the %1, %2, %3 argument variables. o Note that since a function doesn’t return to the line that called it, the code should either end (with exit keyword) or another function should be called. o Note that when using functions, your main code block (before the functions) should also end with exit /B 0. There is much more logic and keywords that can be used in batch files – but this should be enough to get us started. @echo off rem create a couple of folders in your documents cd %userprofile% mkdir documents\school mkdir documents\school\labs mkdir documents\school\tests cd documents\school\labs rem create a couple of files echo Batch File Script > lab1.txt cd.. cd tests echo My Test File > test1.txt echo Second Line >> test1.txt cd %userprofile% @echo off rem A code snipet that test to see if rem the first command line argument is empty if "%1%"=="" ( call :functionTrue ) else ( call :functionFalse %1% ) exit /B 0 rem The true function :functionTrue echo Missing Command Line Arguments... exit /B 0 rem The second function :functionFalse echo %1% exit /B 0 PowerShell Scripting      Text files ending with the extension.ps1 To open a PowerShell command line: search for powershell and select PowerShell from the results (or right-click PowerShell and run as administrator for administrator privileges) o There are many ways to open PowerShell – if you find one you like, stick with it. PowerShell also has an integrated scripting environment (ISE): search for powershell and select PowerShell ISE. Can use both Windows commands and some Linux commands – so both dir and ls work for directory listings. o Interestingly, both dir and ls output is more like Linux than Windows. To run a PowerShell script, either execute it from the PowerShell command line (add a.\ before the command) or right-click on the file and select Run with PowerShell o Note: Most Windows systems have a policy (rules) that restricts script execution. o To check the script execution policy set on your computer use the Get-ExecutionPolicy command in PowerShell. You will get one of the following values:  Restricted: No scripts are allowed. This is the default setting, so you will see it the first time you run the command.  AllSigned: You can run scripts signed by a trusted developer. With this setting in place, before executing, a script will ask you to confirm that you want to run it.  RemoteSigned: You can run your own scripts or scripts signed by a trusted developer.  Unrestricted: You can run any script you want. o To start working with PowerShell, you’ll need to change the policy setting from Restricted to RemoteSigned using the Set-ExecutionPolicy RemoteSigned command PowerShell Cmdlets    PowerShell also has access to.NET cmdlets which are prewritten code files that perform particular functions – like a function or method in C# or JavaScript. o There is system, user and custom cmdlets. o Cmdlets output results as an object or as an array of objects. o Cmdlets can get data for analysis or transfer data to another cmdlet using pipes o Cmdlets are not case sensitive (but there are some cases where other PowerShell programming logic is case sensitive). o If you want to use several cmdlets in one string, you must separate them with a semicolon Cmdlet Format: A cmdlet always consists of a verb (or some action) and a noun, separated with a hyphen (the “verbnoun” rule). For example, some of the verbs include: o Get – To get something o Set – To define something o Start – To run something o Stop – To stop something that is running o Out – To output something o New – To create something To get help, use the get-help command (cmdlet): o Type get-help to get an overview of the help system. o Type get-help dir to get help on the dir command. Note that you do not actually end up running the dir command, instead, it is an alias to the Get-ChildItem cmdlet. So every dir or ls (or gci) done in PowerShell ends up running Get-ChildItem instead. o Since PowerShell is based on.NET which gets updated from time to time, you should update your help system also by typing: Update-Help -force Use the -detailed switch to get more detailed help (sometimes including examples): get-help dir -detailed for more detailed help on the dir command (this would be more helpful with more complicated commands than dir). o Use get-help about* to get a list of conceptual help files that will explain concepts: get-help about_aliases will explain the concept for using aliases. o Using get-help with the asterisk will give you all the cmdlets that matches the pattern: get-help clear* will list the cmdlets starting with the word clear. Use the -whatif switch (or parameter) will tell you what the command will do without actually doing it… o mkdir school -whatif will tell you that the directory school will be created in the current directory (it will show you the exact location). o  PowerShell Logic      Comments o Line comments start with the # symbol o Block comments start with Variables o To declare a variable, use a $ sign before the variable name. o Assign a value to a variable with the assignment (=) operator. o Variables do have a data type, which is determined by the type of value assigned to the variable  $var1 = 2 (var1 will be an int)  $var2 = “Hello” (var2 will be a string) o You can specify the data type of a variable by preceding the variable declaration with the data type in square brackets.  [double]$var3 = 2 (var3 will be a double)  Valid data types include: string, char, bool, int, long, decimal, double, single, DateTime, array (and others) o Variables by default have local scope, to create a variable with global scope (accessible to the whole script), add $Global: before the variable declaration:  $Global:var4 = 2 (var4 will be a global int variable) o You can also assign the output from a cmdlet to a variable  $numberOfCmdlets = (get-command).count where (get-command).count will give you the number of cmdlets available on the computer. Output o To display a variables value, you can just type out the variable name on a separate line (like $numberOfCmdlets) o The Write-Host cmdlet will output text to the screen – which can include the value of a variable:  Write-Host “The number of cmdlets available on your system is $numberOfCmdlets” Using if, if-else, and if-elseif-else determination/selection logic: o Selection logic is formatted like C#: if (condition) { true statements } else { false statements } o The condition has to evaluate to a Boolean (but it doesn’t use the C# comparison operators). o Valid comparison operators include: -eq (equal to), -ne (not equal to), -gt (greater than), -ge (greater than or equal to), -lt (less than), -le (less than or equal to), and there are others. o Valid logical operators include: -and, -or, -xor (only one can be true), and -not (this one is used before the comparison) User-defined Functions o A function must be declared before the function is called – so functions should be the first thing in your code (if you plan on using functions) o To create a function, use the function keyword followed by a name for the function, then include your code inside a pair of curly braces. o Any values passed to a function will be in the $args array – so $args is the first value passed and $args will be the second value passed. o   To call a function, use either its name or its name followed by any value you want passed to the function  Add-Numbers 5 10 will call the Add-Numbers function and pass the values 5 and 10 to the function. o To name a function, it is suggested that you use the Verb-Noun format like PowerShell cmdlets (including the hyphen).  Since PowerShell cmdlet names take precedence over your function names, you want to make sure the function name is not already being used: type help name (where name is the name of the function you want to use) at the PowerShell command line – if help comes up, then that name is used already. To get input from the command line, the easiest (though not the most popular) is to use positional parameters similar to what was used in batch scripting. o Any command line parameters are stored in the $args array – so the first parameter will be $args. Environment variables in PowerShell are stored in a PowerShell drive called env: o dir env: will list all the environment variables and their values o cd $env:userprofile will change the current working directory (cd) to the value ($) of the environment variable (env) userprofile. Use the $ to access the value of the environment variable (instead of % signs before and after the variable like in batch file scripting). # create a couple of folders in your documents cd $env:userprofile mkdir documents\school mkdir documents\school\labs mkdir documents\school\tests cd documents\school\labs # create a couple of files echo "Batch File Script" > lab1.txt cd.. cd tests echo "My Test File" > test1.txt echo "Second Line" >> test1.txt cd $env:userprofile # The true function function Do-NoCmdArgs { Write-Host "Missing Command Line Arguments..." } # The false function function Do-HasCmdArgs { # at this location, args refer to # the function's arguments and not the # command line arguments Write-Host $args } # A code snipet that test to see if # the first command line argument is empty # if no arguments, there will not be a $args # so test for a null value if ($args -eq $null) { Do-NoCmdArgs } else { Do-HasCmdArgs $args }

Use Quizgecko on...
Browser
Browser