How do I write a PowerShell script?

How to write a PowerShell script

PowerShell is a powerful scripting language created by Microsoft that can be used to automate tasks and administer Windows servers and workstations. For several years now, PowerShell has also been available for Linux and macOS. Here's some useful information you need to know about writing a PowerShell script.

In addition to this article, for learn PowerShellI strongly recommend that you read this free course offered by IT-Connect :

1. The basics of writing a PowerShell script

PowerShell is an object-oriented language based on a set of commands and instructions. See commands are called "cmdletspronounced " commandlettes" . There are several thousand of them, not least because PowerShell can handle Windows, but also the various Windows Server roles, Azure and Microsoft 365 services, and more. To add new commands, use themodule installationwhich are listed on the PowerShell Gallery.

Each cmdlet follows a strict naming convention: the name consists of an approved verb followed by a noun. The two terms are separated by a hyphen. For example, the cmdlet Get-Process displays all processes running on your computer. We could almost translate this cmdlet name : Get = Obtenirand Process = Processor " Get processes" .

Each cmdlet contains a set of parameters, i.e. options for influencing the behavior of the command you wish to execute. For example, the New-Item is used to create new items, such as files and folders. It supports several parameters, such as -Path to specify the path of the folder or file to be created, and -ItemType to specify the type of element to be created.

The command below, which you can run in a PowerShell console, is used to create the folder C:\Demo\MyNewFolder.

New-Item -Path 'C:\Demo\MyNewFolder' -ItemType Directory

Another concept to be aware of is the pipeline. The pipeline is essential for passing results from one cmdlet to another. The cmdlet Get-LocalUser is used to obtain a list of all users present on the local machine. What if we only want to retrieve activated users? We'll apply a filter with the Where-Object which is positioned just after the pipeline. In this case, the filter is applied to the Enabled.

Here is the final command:

Get-LocalUser | Where-Object { $_.Enabled -eq $true }

In PowerShell, commands return objects, and each object has a set of propertiesthat is, characteristics. Each object is also associated with methodsIn other words, actions that can be applied to it. If we take the example of a computer, a property could be the CPU model, the RAM model, the power supply, etc... And the methods could be different actions: starting the computer, performing a reset, etc...

PowerShell is a very rich language that supports numerous instructions for integrating loops (For, ForEach, Do-While, etc.), conditional structures (If, If Else, Switch, etc.), and much more... The PowerShell script next is used to check whether there are more than 10 GB available on the "C" volume of the Windows machine.

1TP4DiskSpace = Get-PSDrive C
if (1TP4DiskSpace.Free -lt 10GB) {
    Write-Warning "Insufficient disk space on drive C:"
    Write-Host "Free space: $($espaceDisk.Free)"
}

In the example above, we use a variable named " 1TP4DiskSpace "which is used to store the result of a command. In PowerShell, as you may have guessed, all you need to do is specify a " $ "followed by a name to declare a variable. This variable can be used to store an object, an array, a number, a character string, etc., as required. Calling the variable by its name allows you to read its contents and access the information it stores.

For PowerShell help, you can use the following cmdlets: Get-Help and Get-Member.

2. What software should you use to code in PowerShell?

To code in PowerShell, avoid using basic applications such as Notepad++. I recommend using Windows PowerShell ISEa tool integrated into Windows and Windows Server, or Visual Studio Code with PowerShell. Both of these code editors fully support PowerShell, with VSCode having the advantage of supporting the latest versions of PowerShell.

For routine administration, i.e. execution of commands or ready-to-use scripts, you can use the PowerShell console or the Windows Terminal.

A PowerShell script is represented by a file with the extension ".ps1". This extension has no connection with the version of PowerShell used.

3. Some best practices for coding in PowerShell

Here are some best practices for coding in PowerShell :

1. Use descriptive variable names: choose names that clearly describe the variable's use, to make the code easier to understand. Avoid names like "$a".

2. Comment your code : add comments to explain the logic of your PowerShell script. This will help you and others to understand the code when you come back to it later...

3. Manage errors : use the "try-catch" instruction to handle exceptions and provide clear error messages to facilitate debugging. This will also allow you to act on an error: " if such and such an error occurs, then such and such an action is taken" .

4. Do not use aliases in : aliases can be handy in the console, but they can make the code less readable. Use the full names of cmdlets in your scripts. The list of aliases can be consulted using "Get-Alias".

5. Enter your code: indent your code using the "Tab" key to make it easier to read

6. Test your code : Test your scripts in different environments before running them in production. The use of "-WhatIf" can be useful for this purpose.

In addition, you can use the PSScriptAnalyzer module to analyze your PowerShell script and see if it complies with best practices. This module is included in Visual Studio Code and will analyze your PowerShell script in real time.

4. Conclusion

By reading this article from the IT tutorial box, you'll have useful information to start learning how to write a PowerShell script. Numerous resources are available on the Internet, and Microsoft's documentation is invaluable even after many years of using PowerShell.

Ask your questions in comments and share your tips if you like!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *