Windows 10: PowerShell Scripting - The Basics

Discus and support PowerShell Scripting - The Basics in Windows 10 Tutorials to solve the problem; How to: PowerShell Scripting - The Basics [img] Information A PowerShell script is a collection of commands and cmdlets to be run in logical order,... Discussion in 'Windows 10 Tutorials' started by slicendice, Oct 22, 2017.

  1. PowerShell Scripting - The Basics


    How to: PowerShell Scripting - The Basics

    PowerShell Scripting - The Basics [​IMG]
    Information A PowerShell script is a collection of commands and cmdlets to be run in logical order, previous lines in script determining values and variables in command lines thereafter. The principle is the same than in Command Prompt batch files (.bat or .cmd) but the extended versatility of PowerShell allows much more to be done.

    Quite a lot of Windows 10 maintenance and tasks can be automated with PowerShell scripts. In this tutorial you will learn the basics to get started in using the advanced script editor in PowerShell ISE (Integrated Scripting Environment) to create scripts to automate various tasks.

    To find out more about PowerShell, scripting and cmdlets, see this excellent Microsoft support site: PowerShell Documentation | Microsoft Docs

    Remember that Bing is your friend; you can search for any PS cmdlet to find more information about it and how to use it in scripts. You can also use Get-Help <CMDLET> in PowerShell to find out more about any cmdlet, for instance following command would show you all available information about Start-VM cmdlet:

    Get-Help Start-VM

    PowerShell Scripting - The Basics [​IMG]


    Please notice that this tutorial will only cover the basics to get you started, explaining the most essential facts about scripts and use of variables and conditional statements, which if you ask me are the two most useful things in scripting. Do not hesitate to ask if you have more questions about PowerShell, scripts or individual cmdlets.




    Contents [/i] Use links below to go to any step, back button of your browser to return to this list.


    [table][tr][td]Step One:[/td] [td]PowerShell ISE[/td] [/tr] [tr][td]Step Two:[/td] [td]Set Script Execution Policy[/td] [/tr] [tr][td]Step Three:[/td] [td]Using variables[/td] [/tr] [tr][td]Step Four:[/td] [td]Conditional IF - THEN - ELSE statements[/td] [/tr] [/table]





    Step One [/i] PowerShell ISE
    1.1) Windows 10 comes with two different PowerShell versions, executables for both located in C:\Windows\System32\WindowsPowerShell\v1.0 folder:

    PowerShell Scripting - The Basics [​IMG]


    1.2) Which version to use is totally up to you. The "normal", classic PowerShell (PowerShell.exe) and the modern version PowerShell ISE (Integrated Scripting Environment, PowerShell_ISE.exe) can do the same with two exceptions: First, the normal PowerShell can be switched to classic Command Prompt mode when a legacy command cannot be entered in PowerShell with command cmd and later returned to PowerShell mode with command exit, something PowerShell ISE cannot do.

    An example, PowerShell can be switched to Command Prompt Mode:

    PowerShell Scripting - The Basics [​IMG]


    In PowerShell ISE it can't be done:

    PowerShell Scripting - The Basics [​IMG]


    Second, normal PS can be started by bypassing default script execution policy (see Step 2) simply from RUN prompt with following command and hitting Enter (user mode) or CTRL + SHIFT + ENTER (elevated admin mode):

    PowerShell.exe -ExecutionPolicy Bypass

    PowerShell ISE cannot be started bypassing execution policy. Other than this both PowerShell versions can be used for all actions.

    1.3) PowerShell ISE (from here on PS ISE) which I will use in this tutorial can be found in Start > W > Windows PowerShell > Windows PowerShell ISE. By default it opens showing the Command Add-on list on right, and script pane collapsed. You can toggle Script pane (collapse / expand) from the small arrowhead at right:

    PowerShell Scripting - The Basics [​IMG]





    Step Two [/i] Set Script Execution Policy
    2.1) By default PS does not allow running scripts:

    PowerShell Scripting - The Basics [​IMG]


    2.2) To allow local scripts to be run, go to Settings > Update & Security > For developers, scroll down to PowerShell and click Apply to change execution policy to allow locally created scripts to run:

    PowerShell Scripting - The Basics [​IMG]


    2.3) Doing as told in step 2.2 is enough for us now, to run our own locally created scripts. If you want to allow external (downloaded) scripts to run, use the following cmdlet:

    Set-ExecutionPolicy Unrestricted -Scope CurrentUser


    PowerShell Scripting - The Basics [​IMG]
    Note Unrestricted execution policy might risk your PC by allowing accidentally downloaded malicious scripts to be run. Always be sure only change execution policy temporarily when running a third party script from reliable source, then switch back to restricted policy with following cmdlet:

    Set-ExecutionPolicy Restricted -Scope CurrentUser


    Read more about PowerShell execution policies: Change PowerShell Script Execution Policy in Windows 10 | Windows 10 Tutorials




    Step Three [/i] Using variables
    3.1) A PowerShell command line contains a cmdlet which always has a verb and a noun separated with a hyphen basically telling system to Do This (verb) with That (noun), plus additional parameters

    An example: cmdlet Start-VM with parameter W10PRO would start a Hyper-V VM named W10PRO:

    Start-VM "W10PRO"

    3.2) Quite a lot in in PowerShell in general and scripts in particular is and can be done using variables. A variable name always starts with a dollar sign. For your own variables you can use any name currently not in use. To see a list of all default reserved variable names and for this session by user created variables, type a dollar sign in PS ISE. This will open a drop down list showing all currently existing variables:

    PowerShell Scripting - The Basics [​IMG]



    PowerShell Scripting - The Basics [​IMG]
    Note If PS ISE Intellisense (text predicting) does not show the drop down list, click CTRL + SPACE to open it or right click the command (dollar sign in this case) and select Start Intellisense:

    PowerShell Scripting - The Basics [​IMG]


    3.3) You can use any not already used (reserved) variable name for your own variables.

    3.4) A variable can be used to store any alphanumerical value. If we tell PS that variable $A_Number = 2 (green highlight in screenshot), then ask what's $A_Number * 5 (blue highlight), PS has no difficulties to give correct answer (red highlight):

    PowerShell Scripting - The Basics [​IMG]


    3.5) When a variable contains anything else than a numerical value, we need to put value in quotes. To output (write / show in PS) variable values we use cmdlet Write-Host, which as the cmdlet quite clearly tells in its verb-noun syntax writes (verb) the given variable value to host (noun, current PS session)

    Based on the above, if we give variable $FirstName value "John" (green highlight) and variable $LastName value "Doe" (blue highlight), then tell PS to output both variables using Write-Host cmdlet (red highlight), we'll get John Doe (brown highlight):


    PowerShell Scripting - The Basics [​IMG]


    3.6) Let's use a variable in script. In this sample we ask user which VM he / she wants to start, prompting for input and setting the given string (alphanumerical value) as value to variable $VM

    First line in script would ask user which VM he / she wants to start, setting the name of the VM to a variable $VM:

    $VM = Read-Host -Prompt ' Enter the name of VM, press Enter'

    In command line above, first we tell PS to create a variable $VM. To get value for the variable we use cmdlet Read-Host which tells system to read everything typed until user presses Enter then store the typed string (string = a series of alphanumerical characters) as value for variable $VM. As we want to give user some instructions, we will ad switch -Prompt which allows us to show short instructions for user (prompt text must be in single or double quotes).

    When run, the above command would look like this:

    PowerShell Scripting - The Basics [​IMG]


    3.7) From here on we can use variable $VM instead of virtual machine name, at the moment $VM contains value W10PRO. With following command we could then start the virtual machine $VM:

    Start-VM $VM

    PowerShell Scripting - The Basics [​IMG]


    3.8) Now we can create a script to do the above, combine two commands to one script to ask name of VM to be started and then start it. You can use PS ISE built-in script editor (PS ISE > File > New), Notepad or any other text editor for this. Simply create following script and save it with any name you prefer, with extension .ps1 (PowerShell Script). I will save it to my OneDrive > PS Scripts folder with name StartVM.ps1:

    Code:
    PowerShell Scripting - The Basics [​IMG]
    Note Notice that I added two additional commands at the beginning of the script. First, when script is run I use cls (Clear Screen) command to empty PS window, clear all previous text. Thereafter I use cmdlet Write-Host to write an empty line on top of PS window, just to clarify the output. In line three the script will ask the name of the VM to be started, and line four finally starts it.
    3.9) I can now run the script from PowerShell simply by entering full path preceded with an & sign. Remember, if path contains spaces it must be entered in quotes:

    & "E:\Users\Kari\OneDrive\PS Scripts\StartVM.ps1"

    PowerShell Scripting - The Basics [​IMG]


    Notice the & sign before the path, it is obligatory except when you run a script from your current PS working folder, in which case you enter the name of the script with extension with preceding .\ (.\StartVM.ps1 in this case).




    Step Four [/i] Conditional IF - THEN - ELSE statements 4.1) When anyone on PC I am using to write this tutorial starts PS or PS ISE, a so called PS profile script will be run and user will be greeted with a time based message and the work folder is set to user profile folder:

    PowerShell Scripting - The Basics [​IMG]


    This also in elevated (admin) mode

    My PS profile script is based on IF - THEN - ELSE statement which tells PS that IF THIS condition is met, DO THAT, if condition is not met DO SOMETHING ELSE. To give an example of IF - THEN - ELSE conditional statements, let's create a PS profile script.

    4.2) A PS profile script will be run if it exists. A PS profile for just yourself must be saved in %userprofile%\Documents\WindowsPowerShell folder, and a PS profile for all users in C:\Windows\System32\WindowsPowerShell\v1.0 folder

    4.3) Profile script for normal PS must be named as Microsoft.PowerShell_profile.ps1, and for PS ISE as Microsoft.PowerShellISE_profile.ps1

    4.4) When my sample profile script starts, it will read the current time to variable $Hour in 24 hour format (HH:mm):

    $Hour = Get-Date -Format "HH:mm"

    4.5) In my example case, the current time is told to user in both 24 hour and 12 hour formats. To get both formats, I'll create a new variable $Now, read current time to it and format it to be shown in 24H format (HH:mm) and in 12H format (h:mm tt, single lower case h telling it's 12H format and tt adding AM or PM):

    $Now = Get-Date -Format "HH:mm (h:mm tt)"

    At this point I have current time in 24H time in variable $Hour and in variable $Now the same current time in 24h time plus 12H time in parenthesis.

    4.6) Now the first IF statement. An IF statement syntax is IF (this) then {that}; the word then will not be used and typed but you should think it being there.

    Time comparisons are easier to do using 24H clock. The 24H clock goes from midnight 00:00 to 23:59 (11:59 PM). Time can never be less than 00:00 or more than 23:59. To greet the user when the time using 24H clock is more than 00:00 (after midnight) but less than 06:00 (6 AM), I want to use string "It's quite late", then show the current time in both 24H and 12H formats.

    For that I need to tell PS to do this:

    If the current time in 24H format (variable $Hour) is more than 00:00 but less than 06:00, print (output) "It's quite late %username%. The time is $Now" (time shown in both 24 and 12H formats)

    As a PS command it would look like this:

    If ($Hour -lt "06:00") {Write-Host "It's quite late" $env:username". The time is "$Now}

    Notice that the text I want to output is in quotes (see highlights in above sample), the variables I want to output not.

    The comparison operator -lt means less than. I do not need to use "more than 00:00 but less than 06:00" because for PS 00:00 means zero; all values from 00:00 to 05:59 are covered with comparison operator "less than 06:00". The variable $env:username is a default, built-in variable which has the value of current signed in user.

    4.7) OK, next step is to check if the time is 06:00 or more but less than 12:00 (noon). Using ELSEIF statement after the above IF statement, if its conditions were not met (if the time is more than 06:00) I can write the next line in my PS profile script:

    Elseif ($Hour -lt "12:00") {Write-Host "Good morning" $env:username". The time is "$Now}


    PowerShell Scripting - The Basics [​IMG]
    Note Notice the difference between IF and ELSEIF.

    The first conditional statement in our script checks IF the time is less than 06:00. Next statement uses ELSEIF; an ELSEIF statement is only run if the statement before it was not true, in this case now the first ELSEIF is only executed if the time is 06:00 or more.

    The whole series of IF and ELSEIF statements will stop executing and jump to first command line after the IF - THEN - ELSE command group as soon as the first IF statement or one of later ELSEIF statements is true.

    After that, if both earlier conditions are not met, if it's past noon but before 18:00 (6 PM):

    Elseif ($Hour -lt "18:00") {Write-Host "Good afternoon" $env:username". The time is "$Now}

    4.8) We've covered three quarters of a day. Now the final step: if the time is 18:00 (6 PM) or more, we'll wish Good evening:

    Elseif ($Hour -ge "18:00") {Write-Host "Good evening" $env:username". The time is "$Now}

    The comparison operator -ge means greater or equal, in this sample case now any time between 18:00 (6 PM) and midnight.

    4.9) Final step in my PS profile script is to set default working folder to user profile folder, regardless if user runs normal or elevated PS. That is done with a simple cmdlet:

    Set-Location $env:userprofile

    4.10) Finally I can collect the necessary cmdlets and make the script:

    Code:
    The script as seen in PS ISE Script Pane:

    PowerShell Scripting - The Basics [​IMG]


    You can run any script currently open and active in script pane by pressing F5. This is very practical feature when creating scripts, allowing fast debugging; edit script in script pane, run with F5, if it does not work check the error message and correct script.


    PowerShell Scripting - The Basics [​IMG]
    Note Notice how I improved the readability of my script by separating IF and ELSEIF statements to two rows. Row 1 is the IF THIS part, row 2 is indented (tabbed) containing THEN DO THAT.

    You can do this with all PS script cmdlets, just remember that you can only split commands to separate lines logically, from where a new part of command line starts.

    This works:

    Code:
    This does not work:

    Code:
    That's it. Let's start scripting PowerShell Scripting - The Basics :)

    Kari

    :)
     
    slicendice, Oct 22, 2017
    #1
  2. Andre Da Costa, Oct 22, 2017
    #2
  3. Powershell scripting to join computers to an Azure Domain

    This question is outside the scope of this site (for consumers) and to be sure you get the best (and quickest) answer it should be asked either on Technet (for IT Pro's) or MSDN (for developers)

    Technet forumss/en-US/home

    http://social.msdn.microsoft.com/Forum



    If you give us a link to the new thread we can point some resources to it
     
    ZigZag3143 (MS -MVP), Oct 22, 2017
    #3
  4. cereberus Win User

    PowerShell Scripting - The Basics

    Great tutorial.

    Out of interest, does the elseif support boolean logic e.g.
    (syntax is pseudo code here)

    elseif (a>b or z=g) ......

    type of logic.

    As an aside, I find it quite funny use of textual comparators such as lt, ge etc. Must have been written by a FORTRAN programmer - LOL.
     
    cereberus, Oct 22, 2017
    #4
  5. cereberus Win User
    A second question.

    Is it possible to execute multiple command

    If (a=1) then
    x
    y
    z
    elseif (a=2) then
    f
    g
    h

    endif

    I guess not (and you would need an endif statement I suppose).

    You can of course put endif on each command separately.

    In good old Fortran 66 days, If then else did not exist, and you had to use goto statements all over the place. Coding was like spaghetti!
     
    cereberus, Oct 22, 2017
    #5
  6. No, it does NOT. And there is a reason for this. The < AND > have different purposes and inventing this kind of logic would complicate the simplicity of the language.

    > and < are redirection operators meant to output and input data to/from text files (for instance)
     
    slicendice, Oct 22, 2017
    #6
  7. cereberus Win User
    My use of > and < was just for representative pseudo logic notation, not for syntax accuracy.

    I actually think use of boolean logic makes things clearer.

    If a < 1 do A
    Else a<2 do b
    Else a<3 do c
    Else a>=3 do d

    Is clearer as (imo)

    If a<1 do a
    Else a>=1 and a<2 do b
    Else a>=2 and a<3 do c
    Else a>=3 do d

    Of course in this trivial example, the original is clear enough, but when you get unrelated operators, it can be harder to follow e.g.

    if a<2 or b<a do x

    Is easily split into two lines

    If a<2 do x
    If b<a do x

    how do you easily split up?

    If a<2 and b=a do x

    In Excel for example you can do this by nesting if statements, or use boolean logic.

    Of course, this is all moot, as you cannot do it. I was only asking out of curiosity rather than a specific desire to see such functionality.

    Joys of programming PowerShell Scripting - The Basics :).
     
    cereberus, Oct 22, 2017
    #7
  8. PowerShell Scripting - The Basics

    Sure boolean logic is way more clear than using a parametric aproach. But it becomes very ugly looking when you have to escape each and every operator. If boolean operators would be allowed then we could not have redirection operators and piping operators which are very important in command line executions.

    Let's not get stuck on this issue anymore. One has to understand internal workings of a command-line interpreter in order to understand why all these operators are so important and useful.
     
    slicendice, Oct 22, 2017
    #8
  9. cereberus Win User
    As I said, I was asking out of curiosity, not some pompous criticitism. Only by asking questions, can you explore limitations.
     
    cereberus, Oct 22, 2017
    #9
  10. Kari Win User
    PowerShell has no issues with logical operators. In screenshot beginning of a sample script reading 3 numbers and outputting them in ascending order, comparison in IF statement uses one AND operator (-and in PS) and in ELSEIF statement two AND operators:

    PowerShell Scripting - The Basics [​IMG]


    You can use AND (-and), OR (-or), XOR (-xor) and NOT (-not).


    Yes it is.

    Code: if (this condition is met) { Do this Then do this Finally do this, too }[/quote]
    An IF statement can also include other IF statements:

    Code: if (this condition is met) { if (this condition is met, too) { Do this Then do this Finally do this, too } Do this Do that }[/quote]
     
  11. @cereberus

    I am sorry, I must have used only half my brain this morning and read your question only partially. I did not answer your question at all. Instead I got stuck at your comment about the funny looking operators.

    The correct answer to your question is exactly what @Kari said.
     
    slicendice, Oct 22, 2017
    #11
  12. Tony K Win User
    Great tutorial, Kari.

    Running 10 Pro FCU and Insider 17017. Using PS ISE Admin.

    First things first > Before I get started with learning scripting basics, I was going through the interface to get familiar with it. I see it doesn't have "About" in the help menu. When I click on Help/F1 it takes me to:

    Windows PowerShell Integrated Scripting Environment ISE | Microsoft Docs

    It shows version 5.1 at the left. There's a v6 shown in that drop down menu. In my Windows/System32/WindowsPowerShell/v1.0 the .exe shows as version 1 in properties. Is there a way to get v6?

    I have a PS ISE tile on my Start screen. Is there a way to start the program with Admin rights without going through the UAC prompt? I have to right click the tile and go through its context menu to start in that mode. First-world problem I know. *Biggrin
     
    Tony K, Oct 23, 2017
    #12
  13. cereberus Win User

    PowerShell Scripting - The Basics

    An IF statement can also include other IF statements:

    Code: if (this condition is met) { if (this condition is met, too) { Do this Then do this Finally do this, too } Do this Do that }[/quote]
    Kari[/quote] Thanks very much. I shall have to experiment now PowerShell Scripting - The Basics :).
     
    cereberus, Oct 23, 2017
    #13
  14. cereberus Win User
    No problem - we all have brain fart days.
     
    cereberus, Oct 23, 2017
    #14
  15. Kari Win User
    PowerShell Core, still in beta, is a relatively new version of PowerShell, difference to original native Windows PowerShell being it's open source and can be installed and used in Windows, Linux and Mac. PowerShell Core is currently in version 6.0.0-beta.8: Releases · PowerShell/PowerShell · GitHub

    Although (almost fully) compatible with Windows native PS, I recommend staying in native PS until the time comes that both versions merge to one. Current version of native Windows PS is 5.1:

    PowerShell Scripting - The Basics [​IMG]



    Create an elevated shortcut for it: Create Elevated Shortcut without UAC prompt in Windows 10 Customization Tutorials
     
Thema:

PowerShell Scripting - The Basics

Loading...
  1. PowerShell Scripting - The Basics - Similar Threads - PowerShell Scripting Basics

  2. Issue in Powershell script

    in Windows 10 Gaming
    Issue in Powershell script: HI Team,We have a power shell script. It will check if the user is available in the ACL list of ADL. To get the ACL list, we are connecting to the Azure Datalake storage using Connect-AzAccount and authenticating with SPN. To get the group member details, we authenticate the...
  3. Issue in Powershell script

    in Windows 10 Software and Apps
    Issue in Powershell script: HI Team,We have a power shell script. It will check if the user is available in the ACL list of ADL. To get the ACL list, we are connecting to the Azure Datalake storage using Connect-AzAccount and authenticating with SPN. To get the group member details, we authenticate the...
  4. VBS Visual Basic Scripts

    in AntiVirus, Firewalls and System Security
    VBS Visual Basic Scripts: Im sure most of you know about VBS which stands for Visual Basic Scripts . I just want to talk about what they are and what windows defender see's in them. Now you can make vbs scripts in notepad which is really helpful since its already on your computer! People use it to...
  5. PowerShell script

    in Windows 10 Support
    PowerShell script: The code below tests a series of IPs in a txt file.The result is as follows and is written in a txt file. 19.191.12.161 - online 19.191.12.162 - offline 19.191.12.163 - offline 19.191.12.164 - offline 19.191.12.165 - offline also see the scrennshot Code: $Output= @()$GetIP =...
  6. powershell scripts

    in AntiVirus, Firewalls and System Security
    powershell scripts: Hi, I have azure. Someone is somehow installing powershell scripts onto my computer that allows them to host my PC through P2P and UDP connections, well I think so anyway. I have only just found powershell script entry changes in my registry by accident. These criminals...
  7. powershell script

    in Windows 10 Customization
    powershell script: looking for a script to monitor for a folder, if there is a file in that folder send it as an email, once the email is sent out, confirm and then move the files to an archive folder. monitor c:\test\*.pdf No files, do not send email. Yes Files, send an email to someone at...
  8. Powershell Script on Shutdown

    in Windows 10 Performance & Maintenance
    Powershell Script on Shutdown: Hi all, I try to run a Powershell Script (*.ps1) when i shut down my PC. I created the script and it is working fine when i run it. However if i want to run it on a regular Shutdown it seems like it does not start or is not finished, before Windows is killing every running...
  9. A Powershell Script for HandBrake

    in Windows 10 Software and Apps
    A Powershell Script for HandBrake: Here's the thing. My system is an age-old i3-530 overclocked to 3.5GHz coupled with GTX 1050 2GB. I have around 1.5TB of tutorial videos that I have to encode due to dearth in HDD space. I want to encode the videos while keeping the folder and subfolder structure intact....
  10. PowerShell Scripting - Run a Script from Shortcut

    in Windows 10 Tutorials
    PowerShell Scripting - Run a Script from Shortcut: How to: PowerShell Scripting - Run a Script from Shortcut [img] Information One of many PowerShell security features is that you can't run a script simply by double clicking it's icon on desktop or in a folder. Doing so will by default open script in Notepad for editing...