Fundamental concepts for PowerShell scripting
- Powershell PS1 files
A PowerShell script is a simple text file. The powershell file contains a series of PowerShell commands, with each command appearing on a separate line. For the text file to be treated as a PowerShell script, its filename needs to use the .PS1 extension.
- Powershell Execution Permissions or Policies
Set ExecutionPolicy on the Server
No requirements; all scripts allowed
All local scripts allowed; only signed remote scripts
All scripts need to be signed
No scripts allowed (Scripts won't run.)
You can set PowerShell's execution policy by using the following cmdlet:
e.g. Set-ExecutionPolicy Unrestricted
- Run Powershell Script
First PS1 file
A PowerShell script is really nothing more than a simple text file.
The file contains a series of PowerShell commands, with each command appearing on a separate line.
For the text file to be treated as a PowerShell script, its filename needs to use the .PS1 extension.
- Step 1 :- Create a simple text file.
- Step 2 :- Write any powershell commands
E.g. Get-Process | Sort-Object ID
Note : Get-Process using this you can get a list of processes by using the Get-Process cmdlet, "Sort-Object ID" for the list will be sorted by ID. Use pipe symbol for seperation "|"
- Step 3 :- Rename extension .txt to .PS1 extension (Create at some location with FirstPowershell.PS1 e.g. C:\PowershellScripts\)
- Step 4 :- Open powershell and Run C:\PowershellScripts\FirstPowershell.PS1
- Write Message and Comment Out Command
Pipelining is the term for feeding one command's output into another command. This allows the second command to act on the input it has received. To pipeline two commands (or cmdlets), simply separate them with the pipe symbol (|).
To help you understand how pipelining works, imagine that you want to create a list of processes that are running on a server and sort that list by process ID number. You can get a list of processes by using the Get-Process cmdlet, but the list will not be sorted. However, if you pipeline the cmdlet's output into the Sort-Object ID command, the list will be sorted. The string of commands used looks like this:
Get-Process | Sort-Object ID
You can write console message using command write-host
PS>write-host "Hello World"
Output should be "Hello World"
PS>$TestVarName = "John"
PS>write-host "Hello World" + $TestVarName
Output should be "Hello World John"