PowerShell for Windows and Linux ~ Chapter 1
PowerShell is Microsoft’s proprietary language to do it’s basic to very advanced level tasks. Things like getting Windows Configuration using WMI, settings up server, configuring Active Directory, scheduling events, manipulating Windows Registry, and much more. PowerShell has a variety of modules like Active Directory, Cirtrix POSH, VMware.PowerCLI, Salesforces, ServiceNow, and many more which make it very vast. In this article, we’ll cover Understanding Scripting languages, differences between Configuration Languages and Scripting languages, etc.
Introduction to scripting languages, scripting and configuration management languages
Scripting tools are very handy if we want to automate things. There are a variety of tools and languages including -
- BASH Scripting
- IBM's Job Control Language (JCL)
- Go scripting
And tons more…
Scripting languages in brief -
- Uses interpreter: Scripting languages use an interpreter instead of the compiler (No need to convert code to assembly/machine language)
- Easy learning: Easy to learn and can be edited on the go, unlike compiler-based languages no need to compile once edited.
- Highly Interactive: It helps in adding visualization interfaces and combinations in web pages. Modern web pages demand the use of scripting languages. To create enhanced web pages, fascinated visual description which includes background and foreground colors, and so on.
PowerShell - Important to know
A little theory about PowerShell, I promise not to be boring here.
PowerShell is a cross-platform task automation and configuration management framework, consisting of a command-line shell and scripting language. Unlike most shells, which accept and return text, PowerShell is built on top of the .NET Common Language Runtime (CLR) and accepts and returns .NET objects. This fundamental change brings entirely new tools and methods for automation.
- PowerShell produces the object-based output: What is the object-based output? Let’s understand -
- If I run a command on BASH or SH, it returns a collection of string (a lot of text on screen). On other hand in PowerShell, we get objects (having properties to play with).
- We can play with the object properties, can use the output object as input on other commands. This property makes it very flexible and powerful.
- Pipelines: Pipelines help us to take input from the output of another command.
- Get-Member: To check the object type
- Support for legacy CMD commands and configurable Aliases: PowerShell supports variety of legacy commands used by legacy Command Prompt. We can manually set Aliases for your favorite cmdlets (PowerShell commands called cmdlets).
Starting with PowerShell
PowerShell V/S PowerShell ISE -
- PowerShell: It’s a command-line utility where you run commands one at a time.
- PowerShell ISE: PowerShell Integrated Scripting Environment is a Graphical UI where you can create scripts.
ISE has many great features -
- Syntax highlighting
- Recover unsaved files (Only if ISE closed abnormally)
- Code suggestions tray
- Error highlighting
- Integrated PowerShell inside to run scripts on the go.
- Available on all Current Windows Platforms
- Many more great features…
Launching PowerShell and run basic commands -
Search for PowerShell on your Windows Programs menu (Windows + S to search)
Let's try our first command -
This command returns all running processes on your Windows System as follows (Number or processes could be different in your case) -
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName ------- ------ ----- ----- ------ -- -- ----------- 1914 33 10564 14196 996 0 lsass 907 75 42576 28084 1656 0 SearchIndexer 549 38 6588 5836 49.13 2380 5 AuthManSvr 503 31 8452 11016 102.22 2384 5 AdobeCollabSync 193 19 3092 7168 40.61 3272 5 SecurityHealthSystray 192 10 2592 3496 3572 0 wlanext 64 6 1044 1780 3628 0 ELANFPService 430 31 9304 24532 0.39 3688 5 smartscreen 121 8 1552 1472 4032 0 armsvc 290 22 7344 4088 4084 0 UpdaterService 388 31 18584 6408 4116 0 IntelAudioService 307 12 2452 2652 4344 0 RtkAudUService64
On GUI applications like File Explorer, you generally use
← like buttons to navigate through directories. But here in PowerShell or in BASH, we use commands as bellow -
Set-Location ..Go to one directory back (Parent Directory/Folder)
Set-Location /Go to root directory/Folder.
Set-Location 'c:\path\to\folder'Go to specific folder path.
Set-Location 'NameOfFolder'Go to a folder inside current folder
You can also use Alias
Set-Location, works same.
Checking/listing all available Folders/Files inside.current directory -
Get-ChildItemListing all available folders and Files
dirare alias for
-Forceparameter to display hidden Files/Folders as well)
Building blocks of PowerShell
Nouns are two building blocks of PowerShell. Let's understand this using some examples -
Export, etc.. are starting block of a cmdlet in PowerShell.
LocalUseretc.. are ending block of cmdlet.
Note: PowerShell is not Case-sensitive. Although it's a good practice to use CamelCasing if we have more then one nouns to use. e.g.
LocalUserin this scenario.
Verb-Nouns make a cmdlet. e.g.
Get-Process, Get-EventLog, Get-ChileItem, Set-Location, New-item, etc..
Get-Command * to get list of all available cmdlets on your System.
Parameters are used when we want to manipulate the default values provided in a cmdlet while running it. Let's learn it using an example -
Get-Process gives you all running processes on your Local Machine. If you want to Get processes on remote machine, you need to use
Get-Process -ComputerName “ComputerName” where
-ComputerName is Parameter and
“ComputerName” is value of parameter.
PS C:\Users\kamal > Get-Process -ComputerName "VM-TechAware-1" Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName ------- ------ ----- ----- ------ -- -- ----------- 373 21 7668 1552 0.36 6228 2 AcrobatNotificationClient 514 32 9008 11240 72.50 8392 2 AdobeCollabSync 307 24 4984 6636 32.39 10312 2 AdobeCollabSync 493 36 20684 14376 33.70 3592 2 ApplicationFrameHost 121 8 1524 1416 4088 0 armsvc 272 13 3008 2060 4060 0 AsusLinkNear 188 10 5368 1312 4072 0 AsusLinkRemote 142 8 1540 564 3512 0 AsusOptimization 149 18 2572 2368 28.66 7984 2 AsusOptimizationStartupTask
1. You can use multiple parameters if applicable on that cmdlet.
2. Hyphen ( - ) used before name of Parameter, so that PowerShell can understand difference between Parameters and it's values.
Get-Help cmdlet-namecan be used to know more about commands and it's parameters. You can Check my article PowerShell ~ How to use Get-Help cmdlet to know about Get-Help more.
4. Few parameters can be without values, e.g.
-Forceused for forcefully run cmdlets (Not available for all cmdlets)
Basic commands -
Let's see few daily use commands which you can start practicing with…
Restart-ComputerRestarts your computer instantly.
Restart-Computer -ComputerName “RemoteComputerName”Restarts remote computer instantly. Use
-Forceparameter if user is logged-in on remote computer, and you still want to get it restarted.
Get-Processgets list of all available processes.
Stop-Process -Name 'Notepad'this command will stop Notepad process.
Clear-Hostclears the current PowerShell Screen (Shortcut - Ctrl + L)
Get-Dategives you current date
Get-ComputerInfogives you detailed information about your computer.
You can play with these commands to start with PowerShell
Search for cmdlets using
Get-Command -Name “Get-Computer*”using * you can search on basis of Wildcards.
Use multiple *
Get-Command -Name “*Computer*”if you don't know starting, ending or middle of a command.
Our first PowerShell Script
Let's open PowerShell ISE and write down a script to Add 2 numbers.
# Asking user for input [int]$num1 = Read-Host "Enter 1st number" [int]$num2 = Read-Host "Enter 2nd number" # Doing math $result = $num1 + $num2 # Displaying result Write-Host "The Sum of $num1 and $num2 is $result"
I know above 7 lines script is much difficult to understand if you're not from development background. Let's understand each line one by one.
# Asking user for inputAny line starting with pound (#) is a comment. This will be ignored by PowerShell while running script. Comments make our scripts easier to understand.
[int]$num1 = Read-Host "Enter 1st number"
[int]stands for integer. It is optional in many cases. We have many more variable types like
$num1It's a variable. We can store any kind of value into variables and use them within script.
[int]defined type of variable, so that PowerShell knows what type of value we want users to insert. It is optional.
Read-Hostis a cmdlet which takes any string
"Enter 1st number"as argument. Read-Host reads the input from user.
# Doing mathIt's a comment
$result = $num1 + $num2Here we're defining
$resultvariable which is containing value of SUM of
+is operator used to for addition (
+concatenation in case of adding 2 strings ). There are more operators like
-, *, /, %etc..
%is modules operator returns remainder after dividing 2 numbers.
# Displaying resultit's a comment
Write-Host "The Sum of $num1 and $num2 is $result"write-host used to display something on screen. Using
""you can enter the information you want to display. variables defined with
$will automatically substituted with it's values. Use
''if you want only text to be displayed
Result of above script -
Save the script as
AnyFileName.ps1 run the script on PowerShell ISE, User green color PLAY button.
The result would be similar to this -
PS C:\Users\kamal> C:\Users\kamal\Downloads\add-numbers.ps1 Enter 1st number: 650 Enter 2nd number: 750 The Sum of 650 and 750 is 1400 PS C:\Users\kamal>
PowerShell on Linux
Installation on Ubuntu -
# Download the Microsoft repository GPG keys wget -q https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb # Register the Microsoft repository GPG keys sudo dpkg -i packages-microsoft-prod.deb # Update the list of products sudo apt-get update # Install PowerShell sudo apt-get install -y powershell # Start PowerShell pwsh
Installation on Fedora -
# Register the Microsoft signature key sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc # Register the Microsoft RedHat repository curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo # Update the list of products sudo dnf check-update # Install a system component sudo dnf install compat-openssl10 # Install PowerShell sudo dnf install -y powershell # Start PowerShell pwsh
For other versions of Linux, you can visit Microsoft Docs - Installing PowerShell on Linux
Later on this PowerShell series of lectures, we'll start exploring Microsoft Azure's cmdlets, deploying cloud resources, managing network, etc.