As a software engineer knowing the PowerShell script is the first step or very essential. So let's strengthen our foundation and learn PowerShell with some examples
What is PowerShell?
A PowerShell script is a collection of commands and cmdlets to be executed by the PowerShell runtime. To create a PowerShell script, all you have to do is to create a new text file with the .ps1 extension and then enter your desired commands.
For example, the following script will display the current date and time:
Get-Date
To run a PowerShell script, you can simply type the script file name at the PowerShell command prompt. Alternatively, you can use the Invoke-Expression
the cmdlet to run the script, like this:
Invoke-Expression -Command "& 'C:\Scripts\MyScript.ps1'"
You can also specify arguments for your script by using the -ArgumentList
parameter of the Invoke-Expression
cmdlet. For example:
Invoke-Expression -Command "& 'C:\Scripts\MyScript.ps1'" -ArgumentList "arg1", "arg2", "arg3"
Here are some basic PowerShell commands that you can use in your scripts:
Get-Command
: Lists all available cmdlets.Get-Help
: Displays help for a cmdlet or topic.Get-Service
: Lists all services on the local computer.Start-Service
: Starts a service.Stop-Service
: Stops a service.Get-Process
: Lists all processes running on the local computer.Stop-Process
: Stops a process.Set-ExecutionPolicy
: Changes the execution policy for PowerShell scripts.Out-File
: Sends output to a file.Write-Output
: Sends output to the console.
Here’s an example script that demonstrates some of these commands:
# Get a list of all services
Get-Service | Out-File -FilePath C:\Services.txt
# Stop the "Print Spooler" service
$service = Get-Service -Name "Spooler"
Stop-Service -InputObject $service
# Wait for the service to stop
while ($service.Status -eq "Running")
{
Start-Sleep -Seconds 1
$service.Refresh()
}# Display a message
Write-Output "The Print Spooler service has been stopped."
To import a CSV (Comma Separated Values) file in PowerShell, you can use the Import-Csv
cmdlet. Here's an example of how you can use this cmdlet to import a CSV file:
$data = Import-Csv C:\data.csv
This will create a variable $data
that contains the contents of the CSV file as a series of objects. You can then access the data in the CSV file by using the $data
variable.
For example, to display the first few lines of the CSV file, you can use a Foreach
loop like this:
foreach ($line in $data)
{
Write-Output $line
}
You can also use the Select-Object
the cmdlet to select specific properties from the objects in the $data
variable. For example:
$data | Select-Object Name, Age
This will display the Name
and Age
properties of each object in the $data
variable.
Let's do some practice
To check if IP is in range
Here’s a PowerShell script that you can use to check if an IP address is within a specified range:
function Test-IPAddressInRange
{
param
(
[Parameter(Mandatory = $true)]
[ValidateScript({ Test-IPAddress -IPAddress $_ -Quiet })]
[String]$IPAddress,
[Parameter(Mandatory = $true)]
[ValidateScript({ Test-IPAddress -IPAddress $_ -Quiet })]
[String]$RangeStart,
[Parameter(Mandatory = $true)]
[ValidateScript({ Test-IPAddress -IPAddress $_ -Quiet })]
[String]$RangeEnd
)
# Convert the IP addresses to integers
$ip = [System.Net.IPAddress]::Parse($IPAddress).Address
$start = [System.Net.IPAddress]::Parse($RangeStart).Address
$end = [System.Net.IPAddress]::Parse($RangeEnd).Address
# Check if the IP address is within the range
if (($ip -ge $start) -and ($ip -le $end))
{
Write-Output "IP address is within range."
}
else
{
Write-Output "IP address is NOT within range."
}
}
# Example usage
Test-IPAddressInRange -IPAddress "192.168.0.100" -RangeStart "192.168.0.1" -RangeEnd "192.168.0.255"
This script defines a function called Test-IPAddressInRange
that takes three parameters: an IP address, and the start and end of the range. It converts the IP addresses to integers and then checks if the IP address is within the range by comparing the integer values.
To use the script, you can call the Test-IPAddressInRange
function and pass it the IP address, range start, and range end as arguments. The function will then output a message indicating whether the IP address is within the range.
Check IP is AWS or azure
Here’s a PowerShell script that you can use to check if an IP address belongs to Amazon Web Services (AWS) or Microsoft Azure:
function Test-IPAddressProvider
{
param
(
[Parameter(Mandatory = $true)]
[ValidateScript({ Test-IPAddress -IPAddress $_ -Quiet })]
[String]$IPAddress
)
# Check if the IP address belongs to AWS
$aws = Test-NetConnection -ComputerName "$IPAddress" -Port 80 -InformationLevel Quiet
if ($aws.TcpTestSucceeded)
{
Write-Output "IP address belongs to AWS."
}
else
{
# Check if the IP address belongs to Azure
$azure = Test-NetConnection -ComputerName "$IPAddress" -Port 80 -InformationLevel Quiet
if ($azure.TcpTestSucceeded)
{
Write-Output "IP address belongs to Azure."
}
else
{
Write-Output "IP address does not belong to AWS or Azure."
}
}
}
# Example usage
Test-IPAddressProvider -IPAddress "52.216.128.0"
This script defines a function called Test-IPAddressProvider
that takes an IP address as a parameter. It first checks if the IP address belongs to AWS by using the Test-NetConnection
cmdlet to attempt to establish a connection to port 80 on the IP address. If the connection succeeds, it means that the IP address belongs to AWS.
If the connection to port 80 on the IP address fails, the script then checks if the IP address belongs to Azure by using the Test-NetConnection
cmdlet again. If the connection succeeds, it means that the IP address belongs to Azure. If the connection fails, it means that the IP address does not belong to either AWS or Azure.
To use the script, you can call the Test-IPAddressProvider
function and pass it the IP address as an argument. The function will then output a message indicating which provider the IP address belongs to.
I hope this helps! Let me know if you have any questions or need further assistance.
Powershell script to check if specific software is installed
Here’s a PowerShell script that you can use to check if a specific software is installed on a computer:
function Test-SoftwareInstalled
{
param
(
[Parameter(Mandatory = $true)]
[String]$SoftwareName
)
# Get a list of installed software
$installedSoftware = Get-WmiObject -Class Win32_Product | Select-Object -Property Name
# Check if the software is installed
if ($installedSoftware.Name -contains $SoftwareName)
{
Write-Output "$SoftwareName is installed."
}
else
{
Write-Output "$SoftwareName is NOT installed."
}
}
# Example usage
Test-SoftwareInstalled -SoftwareName "Microsoft Office"
This script defines a function called Test-SoftwareInstalled
that takes a software name as a parameter. It uses the Get-WmiObject
cmdlet to get a list of installed software on the computer, and then uses the Select-Object
cmdlet to select the Name
property of each object.
It then checks if the software name passed as an argument is contained in the list of installed software. If it is, it means that the software is installed. If not, it means that the software is not installed.
To use the script, you can call the Test-SoftwareInstalled
function and pass it the name of the software as an argument. The function will then output a message indicating whether the software is installed or not.