PowerShell: Script

By Xah Lee. Date: .

You can put commonly used commands into a file, save the file, then you can run it as a script.

For example, create a file with the following content:

# filename: test.ps1
Get-ChildItem
get-date

Save this file for example at ~/test.ps1

Run Script

To run a script, type the full path to the script file name

~/test.ps1

or cd to the dir then type script name with ./ in front. The ./ means the current directory.

cd ~/
./test.ps1

for other ways, see Eval {Variable, String, Script, Block}

Execution Policy Error

If this is your first time running a script, you'll get a error like this:

File C:\Users\xah\PowerShell scripts\xx.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing"
for more details.

This is because PowerShell has a execution policy for security purposes. By default, it does not allow you to run unsigned scripts. To make it run unsigned scripts you created on your machine, Run the following to set a different policy:

# make local script run but require remote script to be signed
Set-ExecutionPolicy RemoteSigned

Add Script Dir to $Path

You can add your script dir to the environment variable: $PATH , so you don't have to cd to the dir first to call it.

PowerShell: Profile and Script

PowerShell

Practical How-To

list files

list dirs

on dir

on file

Windows config

zip tar

misc


PowerShell in Depth

Programing PowerShell

Value Types

String

Variable

Boolean

Conditional

Data Structure

Loop and Iteration

Input/Output

Function

Profile and Script

Script Examples