Introduction
Microsoft developed PowerShell, which is a framework for managing and automating tasks. This interactive scripting environment is based on the .NET Common Language Runtime (CLR) and accepts and returns .NET objects. It was first released in 2006 as Windows PowerShell, but it is one of the essentials for now system administrators, developers, and data professionals. PowerShell gives you an administrative interface that you can use to control and automate the management of Windows operating systems and applications that run on Windows. it is a powerful framework for automating tasks and managing configurations. New users often feel overwhelmed by how complicated it seems.
Even though it is important and useful, many people find it scary, mostly because of its command-line interface and many features. But once you learn about its features and how it works, you’ll find that it’s a powerful tool that increases productivity and gives you more control over system management tasks. Today, we want to explore PowerShell and show beginners how to use it.
What Is PowerShell?
In simple terms, PowerShell is a tool for automating tasks that works across different platforms. It has a command-line shell, a scripting language, and a framework for managing configuration settings.
The first version of PowerShell, which is now called Windows PowerShell, was developed in .NET Framework and only worked on Windows, which Microsoft released in 2006. Microsoft announced PowerShell Core in 2016, which is a version that works on all platforms and is built on .NET Core. PowerShell 7 is the name of this version. It works on Windows, macOS, and Linux. PowerShell is not like traditional command-line interfaces, which only use text. Instead, it is built around objects, which are structured pieces of information that can be manipulated in many different ways. Because of this fundamental difference, PowerShell is very powerful and flexible.
The Benefits of PowerShell
If you’re wondering why you should use PowerShell when you can achieve the same activities by using graphical user interfaces (GUIs) in the Windows operating environment, the following are some reasons to consider using PowerShell:
Efficiency: PowerShell is a powerful tool that can automate tasks that you do often. You can use scripts to do things like update system settings or send software to multiple machines. This saves a lot of time and effort.
Consistency: Consistency also means automation. PowerShell makes sure that tasks are done the same way every time, so mistakes made by people are less likely to happen. By using PowerShell scripts, you can make sure that the way you manage things is always the same. This is especially useful in large networks with many servers and workstations.
Control and Capabilities: PowerShell gives more control and capabilities than GUIs. You can do things that are hard to do with GUIs, like perform complex operations, manage machines that are connected to each other, and interact with APIs and other systems.
Automation: PowerShell makes it possible to do a lot of things automatically, which can save a lot of time and cut down on mistakes compared to manual administration. Using PowerShell scripts, you can do the same thing over and over with just one command.
Versatility: PowerShell works with many Microsoft products, like Exchange Server, SQL Server, SharePoint, and more. It can also work with cloud-based services like Office 365 and Azure.
PowerShell Command line Core Concepts
The command-line interface of PowerShell, especially when it comes to PowerShell Core (which was rebranded as simply “PowerShell” in version 7). These are the most important things you need to know about PowerShell. Of course, there’s a lot more to it, but these ideas will get you pretty far.
Cmdlets
PowerShell is built around commands known as cmdlets. They are built-in commands that are written in the.NET language and do certain things. These are simple commands that are each made to do just one thing. They use a syntax called ‘Verb-Noun’, like ‘Get-Process’ or ‘Set-Location‘.
Verb-Noun -Parameter Value
Verb-Noun: Cmdlets are made to be easy to understand and use. They have a verb-noun structure, where the verb describes the action to be taken and the noun represents the thing that the action is done to. For instance, the Get-Content is used to get the contents of a file. The verb part describes the action to do (Get), and the noun part describes the thing to do the action on (Content). A dash(-) separates the verb and the noun.
Here are some more examples to help you understand how verbs and nouns work together:
‘Get-Process’: This cmdlet tells you what processes are running on your system.
‘Stop-Process’: This cmdlet stops a process that is running.
Parameters: Parameters give the command more information about how to run. They start with a dash (-). Some cmdlets don’t need parameters, but if they do, the parameters come after the cmdlet. For example, in ‘Get-Content -Path C:example.txt’, ‘-Path’ is the parameter and ‘C:example.txt’ is the value given to that parameter.
Value: The parameter’s specific information is given by the value. In the ‘Get-Content -Path C:example.txt’ example, the value for the ‘-Path’ parameter is ‘C:example.txt’. With this value, the ‘Get-Content’ cmdlet knows what file to read.
Many cmdlets have optional parameters. Some cmdlets use positional parameters instead of parameter names. Since ‘Get-Content C:\example.txt
‘ is a positional parameter, it works the same as the previous example.
some parameters are referred to be switch parameters since they are optional and need no value like ‘Get-ChildItem
-Recurse
‘ argument instructs to search all sub-directories recursively without a value.
Pipeline
The output of one command (Cmdlet) can be used as the input for another by using pipeline. Data between cmdlets is passed using the pipe character “|”. Pipeline enables to chain commands together for complicated actions, this is tremendously powerful. This makes it possible to combine complicated operations with simpler ones.
`Get-Process | Where-Object {$_.CPU -gt 100}`: This command gets the processes that are using more than 100 units of CPU time. ‘Get-Process’ output sourced as input to ‘Where-Object’ to process.
Aliases
PowerShell allows you to create aliases for Cmdlets. Aliases are user friendly names easy for user to remember and reuse large and complex Cmdlets in short form as well. This can save you typing and make scripts more readable. For instance, `ls` is an alias for `Get-ChildItem`.
Objects
The other main idea is PowerShell’s object-oriented architecture. Unlike most text-based shells, which produce strings of text, PowerShell cmdlets make objects, which are structured data that keeps the order and relationships of its parts and methods that can be used to change the object or as input to other commands.
When you run the ‘Get-Process’ cmdlet, for example, it makes a list of Process objects. These objects have properties like ID, Name, and CPU usage, and operations like Start() and Stop(). These things let you do advanced things that you can’t do with text-based shells.
Variables
PowerShell’s variables are used to store values and other information. They are denoted by the character ‘$’, as in ‘$variable’, when they are defined.
`$myMessage = “Hello, World!”`: This command creates a variable `myMessage` and assigns the string “Hello, World!”.
Scripting
Scripts, which are files that contain a sequence of commands, are something that you are able to build with PowerShell. PowerShell scripts should be saved with extension ‘.ps1’. For instance below script below sequence of commands save them as sysInfo.ps1 file to get the system operating system and hardware information and execute on PowerShell environment.
$systemInfo = Get-ComputerInfo
Write-Host "Operating System: " $systemInfo.OsName
Write-Host "Physical Memory: " $systemInfo.CsTotalPhysicalMemory
> sysInfo.ps1
Operating System: Microsoft Windows 10 Pro
Physical Memory: 17028440064
As a security precaution on most of the environments PowerShell execution policy is set to restricted and to run PowerShell Cmdlets and script it is required to set the execution policy. Below is the process how to check and set execution policy to unrestricted or RemoteSigned to run scripts.
> Get-ExecutionPolicy
Restricted
> Set-ExecutionPolicy RemoteSigned
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help
topic at https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): Y
Modules
Modules in PowerShell are packages that contain PowerShell members such as cmdlets, providers, functions, variables, aliases, and so on. These can also be used to extend the capabilities of PowerShell. Using the ‘Import-Module’ command, you are able to bring modules into your PowerShell session.
> Import-Module myModule
Get-Module Cmdlet gives us information about loaded modules in the session.
> Get-Module
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 3.1.0.0 Microsoft.PowerShell.Management {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest 3.0.0.0 Microsoft.PowerShell.Security {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl, Get-AuthenticodeSignature...}
Manifest 3.1.0.0 Microsoft.PowerShell.Utility {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Script 2.0.0 PSReadline {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSReadLineKeyHandler...}
Providers
Providers are.NET programs that make some type of storage look like a file system. This could be the registry, a SQL database, or anything else that can be read from and written to. Providers in PowerShell let you access different types of data stores, like the file system, registry, or even a SQL Server, as if they were a file system. Use the ‘Set-Location’ and ‘Get-ChildItem’ cmdlets to get to them.
Error Handling
Error management is handled by PowerShell through the use of a number different cmdlets and features, such as the ‘Try’ and ‘Catch’ blocks and the ‘-ErrorAction’ option.
Security
The execution policy, which determines whether or not scripts can be executed, the utilization of secure strings for the management of passwords, and support for certificates and encryption are some of the powerful security features that are available in PowerShell. How to check execution policy and change is demonstrated above in scripting section.
Remote Execution
Through the use of the ‘Invoke-Command’ cmdlet, PowerShell makes it possible to execute commands and scripts on remote machines.
Integration with .NET
PowerShell is built on .NET, and your PowerShell scripts can also directly call .NET classes and methods. This means that you can use the whole of the .NET Framework with PowerShell. You can use the power of .NET in PowerShell to do things like work with file systems, network operations, or databases.
These are just a few of PowerShell’s most basic ideas. Spend some time with each of these to learn how they work and how you can use them to automate your tasks.
PowerShell Scripting
To really use PowerShell’s power, you have to learn how to write scripts. Scripts in PowerShell let you automate tasks that you do often, which makes your work go more quickly. A PowerShell script is just a text file that ends in “.ps1” and has one or more cmdlets in it. Script can include Variables, loops, conditionals, and other common programming tools. In below section we ‘ll explore how to access PowerShell environment and also take a look at on some examples of PowerShell scripts. On Windows Server 2012 R2 and later, we can start Windows PowerShell in the following ways to run PowerShell commands and scripts.
From Startup Menu
- Type “PowerShell” into the search box in the Start Menu Task Bar, and then click Windows PowerShell.
- To run PowerShell as a user with administrative rights Click Start, type “PowerShell“, in search box right-click “Windows PowerShell,” and then click “Run as administrator.”
- Click Start, then All Programs, then Accessories, then the Windows PowerShell folder, and then click Windows PowerShell from the Start menu.
From Command Prompt
- Type cmd in the search box on the Start Menu Task Bar to open the Windows Command shell. Type “PowerShell” at the command prompt to start Windows PowerShell.
Here are a few simple scripts to understand how they created and executed.
For creating a new directory on a specified path.
> New-Item -ItemType Directory -Force -Path D:\Test_Dir
To Read the content of a file and writing a content in a file without opening the file.
# Viewing text file contents
$content = Get-Content -Path D:\file1.txt
Write-Host $content
# Write content to a text file
"This is a text file" | Out-File -FilePath D:\file1.txt
Finding a particular service and start that service
$serviceName = 'SCardSvr'
$service = Get-Service -Name $serviceName
if ($service.Status -eq 'Running') {
start-Service -Name $serviceName
Write-Host "Service $serviceName stopped."
} else {
Write-Host "Service $serviceName is not running."
}
To get the list of running processes and checks each one’s CPU usage. If a process is using more than 100 units of CPU time, the script writes a message to the output.
$processes = Get-Process
for each ($process in $processes) {
if ($process.CPU -gt 100) {
Write-Output "$($process.Name) is using $($process.CPU) CPU time."
}
}
The Future of PowerShell
With the development of PowerShell Core and its ability to work across platforms, PowerShell is likely to become more popular in the future. It’s becoming a vital skill for system administrators, developers, and data professionals. Whether you want to automate tasks, manage system configurations, or process data, PowerShell is a tool you’ll want to learn.
In short, PowerShell is a flexible and powerful tool that can simplify and automate a wide range of tasks. PowerShell might seem complicated at first, but if you learn about its main parts and how they work, it will become much less mysterious. So, roll up your sleeves, start typing in those commands, and find out how powerful this tool really is.
Conclusion
In conclusion, PowerShell might seem hard at first, but if you understand its basic ideas of cmdlets and objects, it will be much easier to learn. PowerShell is more than just a command-line tool; it is also a powerful scripting language that automate tasks. Its integration with the .NET framework makes it even more useful. Whether you are a system administrator who wants to automate tasks or a developer who wants to simplify and unify your toolkit, taking the time to learn PowerShell will definitely pay off.
This article only touched on some of the things you can do with PowerShell. The best way to learn PowerShell is to try out different cmdlets and scripts and learn from your mistakes. With time, the command-line interface, which at first seemed scary, will become a trusted partner in your IT work. So, start learning about PowerShell today and open the door to a world of efficient and automated Windows administration!