# Running Scripts in PowerShell

These are the steps that I had to take in order to create and run scripts in PowerShell. First things first… privileges.

## No Scripts Allowed

PowerShell will not allow you to create scripts and run them by default. If you attempt to do so, you will probably receive the following error message:

File C:\Users\foo\bar.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.

If you run the Get-ExecutionPolicy cmdlet, the default policy is Restricted. This means a blanket prohibition on scripts. The possible Get-ExecutionPolicy values are:

Policy Meaning
Restricted Scripts are prohibited
Default Normally corresponds to Restricted
AllSigned Only scripts with valid digital signatures may be executed.
RemoteSigned Local scripts may be run. Scripts from the Internet or other “public” place must bear valid digital signatures.
Unrestricted Any and all scripts can be executed.

### Setting the Required Privileges

For typical software engineer and power user work, the RemoteSigned setting is appropriate. This will allow you to create, modify, and execute your own scripts while retaining the Internet barrier.

To change the permissions,

1. Run PowerShell with administrator privileges. The execution policy cannot be altered as a normal user.
2. Run the command Set-ExecutionPolicy RemoteSigned

PowerShell will now allow you to run local scripts that you create.

## File Extension

DOS batch files have the extension bat. The default file extension for PowerShell scripts is ps1.

## Execution

PowerShell looks like Unix here. Unless the script is in the Path environment variable — and assuming the script is in your current directory — you will need to mimic the Unix dot-slash notation (using the backslash, of course).

For example, given the script call bar.ps1 in your current directory, if you attempt to run the script directly, you’ll get an error as follows.

PS C:\Users\foo> bar.ps1
The term 'bar.ps1' is not recognized as a cmdlet, function, operable program,
or script file. Verify the term and try again.
At line:1 char:5
+ bar.ps1 <<<< 

Instead you'll have to put .\ in front of the script.

PS C:\Users\foo> .\bar.ps1
Hello, World!

If you do store the script in the directory search path, you will only need to type the file name (without the ps1 extension). This behaviour is similar to batch files.

PS C:\Users\foo> bar
Hello, World!

### In-Process Execution

Also identical to the Unix shell, PowerShell spawns a new process in which to execute the script. If, for example, the script makes changes to an environment variable, that change will be lost when the script terminates.

To execute the script in the current process context, use the dot-space notation:

PS C:\Users\foo> . .\bar.ps1
Hello, World!
This entry was posted in SysAdmin and tagged , , , , , , , , , , , , . Bookmark the permalink.