PowerShell Scripting Introduction


This entry is part 1 of 1 in the series PowerShell Scripting
  • PowerShell Scripting Introduction

Scripting is a very powerful feature of PowerShell. Here we go into detail. For a more general and basic introduction to PowerShell, please have a look at the post called Windows PowerShell Introduction.

Our First Script

All we need to do is to create a text file with a ps1 extension that has a command in it. How about just “Hello World”? Our line of code is Write-Output “Hello World”. It’s easy to do, just as batch files were easy to do back in the days of DOS.

Semicolon

You can use the semicolon to separate commands on the same line. For example, you could run the following after you change the folder structure to match your folder structure.

PS D:\MyData\Portfolio\PowerShell\Scripts> Write-Output "Hello"; Write-Output "World"
Hello
World
PS D:\MyData\Portfolio\PowerShell\Scripts>

Be careful with this. If you want to use the pipeline, you might find that the formatting is unexpected.

Running Scripts

By design, you cannot simply type the name of your script file at the PowerShell command line and expect it to run. It returns an error. It’s for enhanced security reasons and by design. Also, you cannot simply double-click the file in Windows Explorer to get it to run. You get another error that in part says “…is not recognized as the name of a cmdlet, function, script file, or operable program…”.

Below is the contents of the file helloworld.ps1. If you are doing this on your computer you’ll need to create this text file in the folder D:\MyData\Portfolio\PowerShellScriptsSimple (or change the folder after Set-Location).

Write-Host "Hello World"
D:
Set-Location D:\MyData\Portfolio\PowerShellScriptsSimple
Write-Host "Steps"
Write-Host "Open Powershell as Administrator and navigate to the folder containing your scripts."
Write-Host "If your file is called helloworld.ps1 then type the following at the prompt and press enter."
Write-Host "powershell.exe -executionpolicy remotesigned -File helloworld.ps1"
Write-Host "Aside: cd is an alias of Set-Location"