Blog ❯ Author: Fabio Moschini|Date: 27.11.2022
Introduction to PowerShell
Powershell

What is PowerShell
PowerShell is a command-line tool (CLI) for configuring and automating the operating system, its components and other technologies such as SQL Server, Exchange, AWS and Google Cloud.It is cross-platform: available for Windows, Linux and macOS.
In this article we will see some practical PowerShell examples.
Local computer information
Let's see some commands to retrieve information about the local computer.We start with a command that shows BIOS information:The command output is:
SMBIOSBIOSVersion : 7.004
Manufacturer : American Megatrends Inc.
Name : 7.004
SerialNumber : Not Applicable
Version : ALASKA - 1072009
Manufacturer : American Megatrends Inc.
Name : 7.004
SerialNumber : Not Applicable
Version : ALASKA - 1072009
You can view processor information via the WMI class Win32_Processor:The output is:
DeviceID Name Caption MaxClockSpeed SocketDesignation Manufacturer
-------- ---- ------- ------------- ----------------- ------------
CPU0 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz Intel64 Family 6 Model 158 Stepping 10 2201 U3E GenuineIntel
-------- ---- ------- ------------- ----------------- ------------
CPU0 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz Intel64 Family 6 Model 158 Stepping 10 2201 U3E GenuineIntel
To get the computer model information, run this command:
In addition, you can get operating system information via:
To view available space on local disks:whose output is:
DeviceID DriveType ProviderName VolumeName Size FreeSpace
-------- --------- ------------ ---------- ---- ---------
C: 3 510718373888 58673197056
D: 3 Volume 2000381014016 677303054336
G: 3 Google Drive 16106127360 14858432512
-------- --------- ------------ ---------- ---- ---------
C: 3 510718373888 58673197056
D: 3 Volume 2000381014016 677303054336
G: 3 Google Drive 16106127360 14858432512
The option -Filter "DriveType=3" is used to list only data related to hard disks, excluding, for example, SD cards.
To display the current local time:which produces this output:
Day : 12
DayOfWeek : 6
Hour : 15
Milliseconds :
Minute : 3
Month : 11
Quarter : 4
Second : 41
WeekInMonth : 2
Year : 2022
PSComputerName :
DayOfWeek : 6
Hour : 15
Milliseconds :
Minute : 3
Month : 11
Quarter : 4
Second : 41
WeekInMonth : 2
Year : 2022
PSComputerName :
File system operations
In this section we will see how to manage some file system related tasks using PowerShell.List files and directories inside a directory
The -Path parameter, followed by the directory name, defines the path whose contents to display. The -Forceparameter shows hidden and system files. The -Recurseparameter allows listing files and directories at deeper levels. You can filter the list of files to display.For example, to see only files with a certain extension you can use this command:If we wanted to sort files by name, we could use this command:In this case the sorting is ascending.
To force descending sort, specify -Descending:
Copy files or directories
To copy a file use:If the destination file already exists, you can overwrite it by specifying -Force:The command for copying a directory follows a similar syntax:You can specify which files to copy from one folder to another by using the -Filter parameter, for example:Create files or directories
To create a new directory use:Similarly, to create a new file use:The created file will, of course, be empty.Delete files or directories
To delete a directory with all its contents, use:If the directory to delete, the command execution will ask for confirmation. To avoid this prompt, use the -Recurseparameter:Operations on Sql Server
As mentioned, PowerShell can perform operations on a Sql Server instance. For example, we can run a SQL script that creates a table:Note
If we don't specify the Invoke-Sqlcmdparameters -Username and -Password, as in the example, Windows authentication is used.Conditional execution
As in traditional languages, PowerShell scripts can use conditional statements such as IF:or in the form that includes else:To perform multiple comparisons between a variable and its possible values you can use the switch statement:The condition can be an expression containing comparison operators.For example, the equality operator is -eq (case-insensitive) or -ceq (case-sensitive).
The inequality operator is -ne (case- insensitive) or -cne (case-sensitive).
If you need to compare values using "greater than..." or "less than..." operators, you can use:
-gt: greater than... (case-insensitive)
-cgt: greater than... (case-sensitive)
-ge: greater than or equal to... (case- insensitive)
-cge: greater than or equal to... (case- sensitive)
-lt: less than... (case-insensitive)
-clt: less than... (case-sensitive)
-le: less than or equal to... (case- insensitive)
-cle: less than or equal to... (case- sensitive)
Logical operators are also available. For example:
-not or !: the negation operator
-and: logical AND operator
-or: logical OR operator
Loop
There are several types of loops in PowerShell.ForEach-Object
Using ForEach-Object you can loop through all elements of an object.
For example, to list all files in the directory "c:mydir"you could use this script:or:The $_ variable represents the current object inside the loop.
The -Process parameter specifies the operation to execute on each element of the object.
For
The For loop can be used to iterate within a range defined by a minimum and maximum value.
For example, to print multiplication tables we can use this script:You can also use the For loop to iterate over array elements:
While, Do-While, Do-Until
The third type of loop supported by PowerShell is characterized byWhile, Do-While, Do-Until.
In this case the loop continues as long as a certain condition is true or false.
While and Do-While are used to execute an action when the condition is true.
Do-Until has a syntax similar to Do-While, with the difference that the loop runs while the condition is false and ends when the condition becomes true.
For example, to print integers from 1 to 10 you can use this script:or:or:To exit a loop when a certain condition occurs, use the Breakkeyword:
Functions
In PowerShell you can define and call two types of functions:- - without parameters
- - with parameters
- the first syntax allows defining named parameters and uses the keyword param. Example:The function dividiValori can be called like this:or like this:or without naming the parameters but providing the values separated by a space:yielding the same result, since in the first two cases parameters are passed by name while in the third case values are passed by position.
- the second syntax does not use the paramkeyword but allows declaring parameters immediately after the function name:With this syntax parameters are also passed by name, so the following calls:return the same result.
You can call a function recursively.
For example, you could define a factorial function like this:
Error handling
To catch errors that may occur during script execution we can use theTry/Catch construct.Example:As you can easily imagine, the line containing"Questa istruzione non è permessa" generates an error during script execution because the command is not valid.
When the error occurs execution passes to the catchblock where the warning is displayed on a red background.
You can specify an optional Finally block that will execute regardless of whether an error occurred.In the catch block we used the $Error object to display additional information about the error cause.
The properties of the $Error object can be listed with:The returned output is:
|Name |MemberType
|---- |----------
|Equals |Method
|GetHashCode |Method
|GetObjectData |Method
|GetType |Method
|ToString |Method
|CategoryInfo |Property
|ErrorDetails |Property
|Exception |Property
|FullyQualifiedErrorId |Property
|InvocationInfo |Property
|PipelineIterationInfo |Property
|ScriptStackTrace |Property
|TargetObject |Property
|PSMessageDetails |ScriptProperty
|---- |----------
|Equals |Method
|GetHashCode |Method
|GetObjectData |Method
|GetType |Method
|ToString |Method
|CategoryInfo |Property
|ErrorDetails |Property
|Exception |Property
|FullyQualifiedErrorId |Property
|InvocationInfo |Property
|PipelineIterationInfo |Property
|ScriptStackTrace |Property
|TargetObject |Property
|PSMessageDetails |ScriptProperty