PowerShell Re-Introduction Part Four: Our First Script

Part One: More PowerShell: A Re-Introduction If You’re Starting from Scratch
Part Two: PowerShell Re-Introduction: Part Two
Part Three: PowerShell Re-Introduction Part Three: Script Prerequisites

 Okay, let’s say we want a script that will open our Hosts file so we can edit it. Easy, you say. Well maybe.

The first challenge here is that in order to edit and save your Hosts file, you have to run Notepad as an administrator. So if we simply open PowerShell and run Notepad.exe, we’ll can edit the file but we can’t save it; we’ll get an access denied error.

The second challenge is that we have to set the execution policy simply to run a script and we have to run PowerShell as an administrator to even do that.

To demonstrate, right click on PowerShell and select Run As Administrator.

Run Notepad.exe. This will open Notepad.

In Notepad, enter notepad.exe c:\windows\system32\drivers\etc\hosts. CTRL-S to save. Save as Hosts.PS1 it into your PSTest folder you created last time or somewhere else that’s convenient. Note, here, that .PS1 is the recognized extension for PowerShell script files and they are that easy to build, in Notepad or other test editor much like DOS batch files.

Now, in PowerShell, navigate to your PSTest folder where the script live and enter DIR. You’ll get a directory listing of your folder. Why, Well, like we learned last time, if you run Get-Command DIR, you’ll see that it’s the same as Get-ChildItem.

In our directory listing, you’ll see your .PS1 file. We can run this from here:

Script Execution Error

Script Execution Error

 Okay, maybe not so much.

First, it’s telling us our command is not recognized, check spelling and path. That’s not our problem.

Then it tells us our file exists but was not found. If we want PowerShell to find it, we have to build some some context into our command using .\<Command> format made famous by our Linux friends. Let’s try it.

Execution Policy Error
Execution Policy Error

Different Error. This is our Execution Policy stopping us.

So, lets run Set-ExecutionPolicy Unrestricted. This requires us to confirm by entering Y.

Now, when we run .\Hosts.PS1, our hosts file opens and we can edit it, save it and close it.

Now, this is good but not great. What we’d like is a file we can click on in Windows Explorer, set the execution policy and open the file. When you right click on the .PS1 file, you don’t get a Run As Administrator option.

Well, one way to do this is to create a shortcut to PowerShell.exe and pass it your script file as a test string like this:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe “C:\PSTest\Hosts.PS1”

 Then you can right-click on the shortcut and run it as an administrator.

There’s your first script. We’ll look at different persmission options. more sophisticated scripts, and the ISE next time.





Comments are closed.