PowerShell is a command-line shell and an object-oriented scripting language. It is built on .NET framework that provides a cross-platform support for Windows, macOS and Linux. PowerShell commands are called cmdlets. It is used by IT administrators and help desk workers for simplifying configuration and task automation. PowerShell providers let the users access to different data stores, like file system or registry. The most recent version available are PowerShell 5.1 for windows-based system and PowerShell 7 for Windows, macOS and Linux.
The reasons to learn PowerShell are as follows:
Easy Automation
Each cmdlet can be used separately. It is used to perform complex tasks. PowerShell consists of more than a hundred basic core cmdlets. Users can also write their own cmdlets and share it with other users. The skills to design cmdlets and perform PowerShell scripting are high in demand for companies throughout various countries.
Scalable Management
PowerShell can be used to design cmdlet script for various task. For example, installing operating system updates on 500 PC can be done through a cmdlets script designed to perform more than a couple of times.
Accessing Information
PowerShell providers allows users to access data and information. For example, IT admins can easily get access into secure data stores such as file system or registry. Unlike most CLIs, it is built on Microsoft .NET framework which allows IT professionals for automation and performing of special task on Windows computer. It also provides control over network resources just by typing a line of command-line code.
Get-Help – Displays information about PowerShell commands and concepts. To get help, simply type Get-Help followed by the name such as:
Get-Help -Name Get-Service
To get specific help, the user can also use parameters such as:
Get-Help
[[-Name] <String>]
[-Path <String>]
[-Category <String[]>]
-Parameter <String[]>
[-Component <String[]>]
[-Functionality <String[]>]
[-Role <String[]>]
[<CommonParameters>]
1.1. -Name: Get help about specific command, functions, provider, scripts or workflow.
1.2 -Path: Get help that explains how cmdlet works in specific path.
1.3 -Category: Displays help for item in specific category.
1.4 -Parameter: Displays details of specific parameter.
1.5 -Component: Displays specified component values.
1.6 -Functionality: Displays help for items with specified functionality.
1.7 -Role: Displays help for the specified user role.
Set-ExecutionPolicy – This command is used to set the execution policy in the computers. There are four types of execution policy such as: Restricted, All Signed, Remote Signed and Unrestricted. To set the execution policy, enter the Set-ExecutionPolicy command followed by the policy name. For example: Set-ExecutionPolicy -ExecutionPolicy AllSigned
Get-ExecutionPolicy – This command is used to get the execution policy that is in use before running the script. For example: Get-ExecutionPolicy -List. This command gets all the list of each scope’s execution policy.
Get-Service – This command is used to get the list of services that exist on the computer. It can also be used to get particular service by specifying the parameters such as: Get-Service -Name "win*" -Exclude "wisvc"
ConvertTo-HTML – This command converts an object into HTML that can be displayed in Web browser. It can also be used with other command such as: Get-Service | ConvertTo-HTML -Property Name, Status > C:\services.htm. This command will create a HTML file with the list of names of services with its status.
Get-EventLog – This command is used to get all the event logs that are available on the computer. There are several parameters that can be used with this command. For example: Get-EventLog -List. This command will display the list of event log that are available on the computer.
Get-Process – It displays all the processes that are running on the computer. The user can also specify the process by using parameters. For example: Get-Process winlogon | Format-List *. This command will get all the data about winlogon and the pipeline operator (|) passes the data to Format-List command which will display all the list of names of the properties of winlogon process objects.
Stop-Process – When the process freezes up, Get-Process command can be used to get the name or id of the process and Stop-Process command can be to stop that process. For example: Stop-Process -Name “TextEdit”. This command will stop all the instances of TextEdit on the computer.
Select-Object – This command is used to select specific properties of an object. It can also select specified number of objects or objects in an array. For example: Get-Process | Select-Object -Property Name, Id. This command creates objects that have the name and id properties of process objects.
Export-CSV – This command is used to export data from PowerShell into CSV file. For example: Get-Service | Export-CSV c:\servicefile.csv. This command export list of services to a servicefile.csv
IF statement
Curly brackets ({}) must be used to open and close if statement. It executes the script block if its condition is true.
ELSE IF statement
Executes the script block if its condition is true and none of the if/elseif condition before it is true.
Else
Executes the script block if none of the if/elseif condition before it is true. For example:
$number=30
If ($number -lt 10)
{
“Number is less than 10”
}
else if ($number -gt 10)
{
“Number is greater than 10”
}
else
{
“Invalid Number”
}
The output will be:
Number is greater than 10
For loop
Creates a loop that runs command in command block when the specified condition is true. It is mostly used to iterate all values in an array. For example:
$array=@(“N1”, “N2”, ”N3”)
for ($i=0; $i -le $array.length; $number++)
{
$array[$i]
}
The output will be:
N1
N2
N3
Foreach loop
Iterate a series of values in a collection of items. Foreach statement consists of variable and a collection to iterate. Each iteration sets the variable with the item of collection. For example:
$array = @("a","b","c")
foreach ($letter in $array)
{
$letter
}
The output will be:
a
b
c
WHILE loop
Creates a loop that executes the command block as long as the condition remains true. Unlike foreach statement, a condition is specified in the while statement that controls how many loops to run. For example:
$array = @("a","b","c")
$count=0;
while($count -lt $array.length)
{
$array[$count]
$count = count + 1
}
The output will be:
a
b
c
DO-While loop
Runs the script block, subject to While condition. The statement in the script block runs at first and then the condition is evaluated. For example:
$array = @("a","b","c")
$count=0;
do
{
$array[$count]
$count = count + 1
} while($count -lt $array.length)
The output will be:
a
b
c
PowerShell Script that will look in the current directory, and all directories contained within, for files with extension *.java and invoke the javac command on each of them (to compile them). (See the figure A below)
Get-ChildItem -Path .\* -Include *.java -Recurse -Force
This command displays .java files that are located in the current directory and its subdirectories.
$javafiles=Get-ChildItem -Path .\* -Include *.java -Recurse -Force
All the java files are stored in this variable file ($javafiles).
foreach($file in $javafiles
{
Write-Host “Compiling …” $file
javac $file
}
This foreach loop consist of two parentheses, a variable ($file) that will represent the item from collection and the variable that is holding the collection of files($javafiles).
In the first iteration, the loop sets the variable ($file) equal to the first item in collection ($javafiles), then Write-Host $file cmdlet displays “Compiling …” along with the value of variable and javac $file cmdlet complies that variable ($file) into java class file. The next loop, the variable is set equal to the second item in collection and so on. The loop exists after iterating all the item in the collection.
Write-Host "List of Compiled files"
It displays the output “List of Compiled files”.
Get-ChildItem -Path .\* -Include *.class -Recurse -Force
After the completion of looping, this command will display all the compiled java class files.
In order to test this script, a skeleton folder structure was created, and some empty (zero-bytes) Java files, text files and some java files with source code were inserted in various parts of the folder structure.
new-item -ItemType Directory -Path ~/dir1/dir2/dir3
It creates dir1 directory with dir2 as its subdirectory and dir3 as the subdirectory of dir2.
new-item -Path . -Name "file1.java"
The New-Item command was used to create some empty java files and some java files with source code and some text files in each directory. (See the figure B below)
Figure B shows all the files created in directory and its subdirectories.
.\testscript.ps1
The PowerShell script was executed to test if it compiles all the java files from the current directory and its subdirectories. (see figure C)
It displays all the name of the java files from the current directory and its subdirectories and also displays the list of java file that were compiled to java class file.
It shows that all the java files are compiled to java class file except the empty ones (e1.java and e2.java) because if there is no class declared in the java file, the java class file cannot be created.
A script that looks in the current directory and its descendants for folders containing the two files (hello.exe and script.ps), deletes each file, then deletes the containing directory. (See the figure E below)
Get-ChildItem -Directory -Recurse
This command gets the current directory and its subdirectories, and the variable ($dirs) is used to store it.
foreach($dir in $dirs)
$jp1= Join-Path -Path $dir -ChildPath $virus1
$jp2= Join-Path -Path $dir -ChildPath $virus2
if((Test-Path $jp1) -and (Test-Path $jp2))
{
Remove-Item $jp1
Remove-Item $jp2
Remove-Item $dir -Force
}
Foreach loop iterates over the directories. In the first iteration, $dir will be set to the first directory that was retrieved by Get-ChildItem command. The join-path command will attach the virus files to that directory. The variable $jp1 and $jp2 stores the joined path. The if loop with Test-path cmdlet checks if that joined path exists or not. If it comes true, then the remove-item will remove the joined path which represents the virus file and removes the directory that contained that virus file. In the next iteration, $dir is set to the second directory and the same process follows.
To test this PowerShell script, the virus files (hello.exe and script.ps) were inserted into directories. And the PowerShell script was executed to check if it deletes the virus file and its directory.
mkdir command was used to create the directories and subdirectories and New-Item cmdlet to create virus files in the directories. (See the figure F below)
The virus file was created in v2 directory and v4 directory.
.\detectvirus.ps1
The script was executed and all the directory that had virus file was deleted without any errors. (See the figure G, figure H. and figure I below)
The script executed without any errors.
The Get-ChildItem cmdlet was executed to display the directory with its subdirectories. There were no subdirectories found because they had virus files in it and the script deleted those files and its directories.
It shows that only the PowerShell script was present in the directory which proves that the virus files and its directory were deleted.