This is part 6 in a series of posts related to Windows PowerShell, and deals with getting to grips with scripts..
So far – we have been typing commands into the PowerShell console (or the ISE) but what happens if you want to create some functionality which you can reload at a future session. The answer is to create your PowerShell commands as a PowerShell script.
You can either go hard-core and use something like Notepad (or your text editor of choice) to create the script, or you can use the ISE to create and save your script. When saving the script – give it a “.ps1” file extension so PowerShell knows that it’s a script file and not a text file. The extension comes from PowerShell 1.0 and they didn’t feel the need to change the extension for PowerShell 2.0. As you would expect – PowerShell 2.0 can run PowerShell 1.0 scripts, but the reverse is not guaranteed.
Let’s start with our first script – the typical Hello World script!
Save this as HelloWorld.ps1 (or similar). To make your life easier for the moment – make sure there is no space in the file name or anywhere in the path that contains the file name. We’ll worry about handling spaces in a later post.
The logic for this script is extremely simple:
- Clear the output
- Prompt the user their name and store in a variable
- Say hello and repeat the users name by accessing the variable.
You have a number of choices to run this script:
- Run it from inside the ISE by pressing F5
- Run it from inside the ISE or PowerShell Console by typing the script name (including path) into the command prompt
- Run it from a standard console prompt by using the following: powershell [FilePath]\HelloWorld.ps1 where [FilePath] is your relevant directory structure. In my case – my script is stored on my desktop so I’m executing powershell c:\Users\IvorB\Desktop\HelloWorld.ps1"
There you go – you should now have a working Hello World script!
As mentioned in Part 4 of this blog series – security measures are in place to prevent scripts executing without your permission. You have 2 choices at this stage – to digital sign your script, or to adjust your execution policy to allow execution of unsigned scripts. The easiest (and laziest) way to get this to work is to change the execution policy which you can do with the following command:
Set-ExecutionPolicy RemoteSigned.
Next step – What the heck is a Cmdlet?
Previous step – The Integrated Shell Environment (ISE)
Technorati Tags:
PowerShell