How To Run Powershell Scripts
Powershell scripts are used to complete tasks simply running script files. This provides easy to use way to run same commands again and again. Scripts also used to share experience with other system administrators easily. Scripts may need sometimes parameters to operator. In this tutorial we will look different aspects and usage forms of Powershell scripts.
Enable Powershell Script Execution with Execution Policy
Securit is important topic todays. Microsoft have learned a lot of things from previous mistakes. It created some security mechanisms for its powerful scripting engine Powershell.
Print Current Execution Policy
Get-ExecutionPolicy is used to list current status of the execution policy. We will get like belolw.
As we can see that current execution policy is
Restricted which simply means we can not run downloaded powershell scripts.
Enable Execution Policy
We can change powershell execution policy with
Set-ExecutionPolicy command by specifying the new policy name. We will allow all scripts by specifying policy named
Unrestricted . In order to change the current shell should have Administrator privileges.
PS> Set-ExecutionPolicy Unrestricted
We will simply answer
Y to the confirmation question.
Create Simple Script
In order to use in test we will create a script file named
helloworld.ps1 which contains following script.
ps1 is used to specify the powershell script and the v
echo "Hello World"
Run Script In The Current Directory
We can simply run the script which resides in the current directory. In this example we will run
. is the current working directory.
Path with Spaces
Spaces have different meaning in Powershell and path or file names with spaces must be surrounded with double
' single quotes.
PS> ".\hello world.ps1"
Using Invoke Command Commandlet
Invoke-Command commandlet for command invocation. We can use this for script call. More detailed about
Invoke-Command can be found below.
Run With CMD.exe
We can call different shells from Powershell. For example we can call
python commands and script from Powershell by specifying python interpreter. We can also run
cmd.exe to call MS DOS scripts like below. But keep in mind that MSDOS can only run
PS> cmd.exe /C helloworld.bat