Join-Path is a PowerShell cmdlet that combines a base path and a child path into a single one. This is useful for constructing file or directory paths dynamically. The syntax for using Join-Path is:
Join-Path -Path <base path> -ChildPath <child path>
Here's an example of using Join-Path to create a file path:
$directory = "C:\MyFolder"
$filename = "example"
$path = Join-Path -Path $directory -ChildPath "$($filename).txt"
In this example, $directory is the base path, $filename is the child path, and "$($filename).txt" is the desired file extension. Join-Path combines these to create the full file path, which would be "C:\MyFolder\example.txt".
The Invoke-WebRequest
PowerShell cmdlet is used to fetch content from a web page on the internet. It allows you to make HTTP requests, retrieve HTML content, and interact with web APIs directly from your PowerShell script.
Gets content from a web page on the internet.
# Here we are asking Google about PowerShell and saving the response
$Response = Invoke-WebRequest -URI https://www.google.com/search?q=powershell
# We use the Content property of $Response to access the webpage content
$Response.Content
In the example above, $Response
will store the content retrieved from the specified URL (https://www.google.com/search?q=powershell
). You can then use $Response
to parse and extract information from the web page as needed.
To learn more about Invoke-WebRequest
, you can visit the Microsoft documentation page. This resource provides detailed information and examples to help you understand and use this cmdlet effectively.
In PowerShell, you can show elapsed time using a simple timer script. Start by capturing the current time when your script begins with $StartTime = $(Get-Date)
. Then, calculate the elapsed time by subtracting the start time from the current time: $elapsedTime = $(Get-Date) - $StartTime
. Format the elapsed time into hours, minutes, and seconds using the "{0:HH:mm:ss}"
format and apply it to a DateTime object: $totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
.
$StartTime = $(Get-Date)
# Your script here
$elapsedTime = $(Get-Date) - $StartTime
$totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
Write-Host "Total elapsed time: $totalTime"
For more details and discussions, you can refer to this Stack Overflow post.
Writes customized output to a host.
Write-Host [[-Object] <Object>] [-NoNewline] [-Separator <Object>] [-ForegroundColor <ConsoleColor>] [-BackgroundColor <ConsoleColor>] [<CommonParameters>]
The Write-Host
cmdlet's primary purpose is to produce for-(host)-display-only output, such as printing colored text like when prompting the user for input in conjunction with Read-Host. Write-Host
uses the ToString() method to write the output. By contrast, to output data to the pipeline, use Write-Output or implicit output.
Write-Host "no newline test " -NoNewline
Write-Host "second string"
no newline test second string
Further information can be found at Write-Host (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Docs.
Selects objects or object properties.
The Select-Object
cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array.
To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters. To select object properties, use the Property parameter. When you select properties, Select-Object
returns new objects that have only the specified properties.
Example 1: Select objects by property
This example creates objects that have the Name, ID, and working set (WS) properties of process objects.
Get-Process | Select-Object -Property ProcessName, Id, WS
Select-Object (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Docs
In real-time application requirements, we will work with a custom PowerShell object array (complex object) instead of a simple string or integer array. The Unique switched parameter can also be used to find distinct objects by a property in a custom object array.
# Initialize the array $Array = @() $Array += [PSCustomObject]@{ Name = "User1"; } $Array += [PSCustomObject]@{ Name = "User2"; } $Array += [PSCustomObject]@{ Name = "User2"; } $Array += [PSCustomObject]@{ Name = "User3"; } $ResultArray = $Array | Select-Object -Unique -Property Name $ResultArray # Result array with unique Name values Name ---- User1 User2 User3
As already explained, the Unique parameter with Select-Object cmdlet finds unique values with case-sensitive string comparison. If you work with a string property and want to perform a case-insensitive string comparison to find distinct objects, then we need to use the Unique parameter with Sort-Object cmdlet to perform a case-insensitive check.
# Initialize the array $Array = @() $Array += [PSCustomObject]@{ Name = "User1"; } $Array += [PSCustomObject]@{ Name = "user2"; } $Array += [PSCustomObject]@{ Name = "User2"; } $Array += [PSCustomObject]@{ Name = "User3"; } # Find unique objects by case-sensitive comparison. $Array | Select-Object -Unique -Property Name Name ---- User1 user2 User2 User3 # Find unique objects by case-insensitive comparison. $Array | Sort-Object -Unique -Property Name Name ---- User1 User2 User3
There are three methods to create and define an array. Based on these three methods, below are the three syntaxes of a PowerShell array:
In the first syntax, an array is created by enclosing the items in the @() parentheses.
$ArrayList = @('item 1', 'item 2', 'item 3')
The second syntax creates an array with items in a comma-separated list.
$ArrayList = 'item 1', 'item 2', 'item 3'
The third syntax creates an array with a specific data type.
[ArrayType[]]$ArrayList = 'item 1', 'item 2', 'item 3'
We can use the .NET’s string extension function StartsWith to check whether a string starts with a set of characters.
The following method is used to check if a string starts with another string.
$strVal ='Hello world'
if($strVal.StartsWith('Hello')) {
Write-Host 'True'
} else {
Write-Host 'False'
}
Use the following method if you want to ignore the case in the start with check.
$strVal ='Hello world'
if($strVal.StartsWith('hello','CurrentCultureIgnoreCase')) {
Write-Host 'True'
} else {
Write-Host 'False'
}
Module: Microsoft.PowerShell.Utility
Creates table-like custom objects from the items in a comma-separated value (CSV) file.
Import-Csv [[-Delimiter] <Char>] [-Path] <String[]> [-Header <String[]>] [-Encoding <Encoding>] [<CommonParameters>]
The Import-Csv
cmdlet creates table-like custom objects from the items in CSV files. Each column in the CSV file becomes a property of the custom object and the items in rows become the property values. Import-Csv
works on any CSV file, including files that are generated by the Export-Csv
cmdlet.
Import-Csv (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Docs
How to use PowerShell to read a line from a text file.
First read from a text file using Powershell. Then using the loop named FOREACH.
$file = Get-Content "C:\File.txt" foreach ($line in $file) { Write-Output "The name is: $line" }
Module: Microsoft.PowerShell.Core
Performs an operation against each item in a collection of input objects.
ForEach-Object [-InputObject <PSObject>] [-Begin <ScriptBlock>] [-Process] <ScriptBlock[]> [-End <ScriptBlock>] [-RemainingScripts <ScriptBlock[]>] [-WhatIf] [-Confirm] [<CommonParameters>]
The ForEach-Object
cmdlet performs an operation on each item in a collection of input objects. The input objects can be piped to the cmdlet or specified by using the InputObject parameter.
Starting in Windows PowerShell 3.0, there are two different ways to construct a ForEach-Object
command.
Assuming a CSV file as such:
Name, Address, City name1, Address1, city1 name2, Address2, city2 name3, Address3, city3
We will use Import-Csv
to populate the objects from a CSV file. With $csv.Name
we will retrieve all cells in the Name column and pass this to the ForEach-Object
cmdlet to loop through each item. In this loop, we will just output the name.
$csv = Import-Csv "C:\File.csv" $csv.Name | ForEach-Object { Write-Output "The name is: $_" }
Tags are used to organize the deployed resources in the Azure cloud, we could search the resources by tag key and value.
List all the resources with a specific tag key
Get-AzResource -TagName "Environment"
List all the resources with a specific tag value
Get-AzResource -TagValue "Test"
List all the resources with a specific tag key and value
Get-AzResource -Tag @{Environment="Test"}
Get-AzConnectedMachine
The Get-AzConnectedMachine
cmdlet can be used to retrieve information about the hybrid machine and pipe them to the Where-Objet to filter by the tag name and tag value.
Get-AzConnectedMachine | Where-Object {( $_.Tag.Keys -eq $TagKey) -and ($_.Tag.Values -eq $TagValue)} | ft Name, Tag
Get-AzResource cmdlet
The Get-AzResource cmdlet can be used for any type of Azure resource and we will filter for Azure Arc using the -ResourceType parameter with Microsoft.HybridCompute/machines value
Get-AzResource -ResourceType Microsoft.HybridCompute/machines
As described in Get Azure Resources based on Tags in PowerShell we can extend this sample with parameters for the tag name and tag value.
Get-AzResource -ResourceType Microsoft.HybridCompute/machines -TagName $TagName -TagValue $TagValue
Selects objects from a collection based on their property values.
Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] [-EQ] [<CommonParameters>]
The Where-Object
cmdlet selects objects that have particular property values from the collection of objects that are passed to it. For example, you can use the Where-Object
cmdlet to select files that were created after a certain date, events with a particular ID, or computers that use a particular version of Windows.
Example 1: Get stopped services
Get-Service | Where-Object {$_.Status -eq "Stopped"} Get-Service | where Status -eq "Stopped"
Where-Object (Microsoft.PowerShell.Core) - PowerShell | Microsoft Docs
The Where−Object
or (alias: Where) in PowerShell is used to filter the data output provided through the pipeline.
To get the Services with the StartType AUTOMATIC and the status STOPPED we can use a script block to filter the output with the Property name, value, and the comparison operator.
Get−Service | Where−Object{($_.StartType −eq 'Automatic') −and ($_.Status −eq 'Stopped')}
You can also use Alias: Where instead of Where−Object.
Get−Service | Where{($_.StartType −eq 'Automatic') −and ($_.Status −eq 'Stopped')}
Other Syntax ‘?’ (Question Mark) can also be used Instead of the Where−Object command.
Get−Service | ?{($_.StartType −eq 'Automatic') −and ($_.Status −eq 'Stopped')}
See also the Where-Object cmdlet in PowerShell
Module: Az.ConnectedMachine
Retrieves information about the model view or the instance view of a hybrid machine.
Get-AzConnectedMachine [-SubscriptionId <String[]>] [-DefaultProfile <PSObject>] [<CommonParameters>]
Retrieves information about the model view or the instance view of a hybrid machine.
Example 1: List all connected machines in a subscription
Get-AzConnectedMachine -SubscriptionId 67379433-5e19-4702-b39a-c0a03ca8d20c Name Location OSName Status ProvisioningState ---- -------- ------ ------ ----------------- winwestus2_1 westus2 windows Connected Succeeded linwestus2_1 westus2 linux Connected Succeeded winwestus2_2 westus2 windows Connected Succeeded winwestus2_3 westus2 windows Connected Succeeded
Get-AzConnectedMachine (Az.ConnectedMachine) | Microsoft Docs
The get the absolute path given a relative file path Resolve-Path cmdlet can be used.
Resolve-Path ".\filename.txt" Path ---- C:\Path\filename.txt
To write to a relative path the Set-Content cmdlet can be used
"Content" | Set-Content ".\filename.txt"
Gets preferences for the Windows Defender scans and updates.
Get-MpPreference [-CimSession <CimSession[]>] [-ThrottleLimit <Int32>] [-AsJob] [<CommonParameters>]
The Get-MpPreference cmdlet gets preferences for the Windows Defender scans and updates. For more information about the preferences that this cmdlet retrieves, see Windows Defender Preferences Class.
Example to view the scheduled scan day
$Preferences = Get-MpPreference
$Preferences.ScanScheduleDay
Details about the preferences for Windows Defender scans and updates can be found in Set-MpPreference PowerShell Cmdlet.
For additional details visit Get-MpPreference (Defender) | Microsoft Docs.
Module: Defender
Configures preferences for Windows Defender scans and updates.
The Set-MpPreference cmdlet configures preferences for Windows Defender scans and updates. You can modify exclusion filename extensions, paths, or processes, and specify the default action for high, moderate, and low threat levels.
Example to schedule to check for definition updates everyday.
This command configures preferences to check for definition updates every day.
Set-MpPreference -SignatureScheduleDay Everyday
Additional examples at Schedule antivirus scans using PowerShell | Microsoft Docs
Details about the cmdlet at Set-MpPreference (Defender) | Microsoft Docs
To access an item in an array we can use an index.
$ArrayList = @('item 1', 'item 2', 'item 3')
$ArrayList [1]
item 2
Small script to remember how to update Tag for all VM in particular resource group:
$tags = @{“tag01″=”value1”; “tag02″=”value2”; “tag03″=”value3”}
Get-AzResource -ResourceGroup todelete -resourcetype Microsoft.Compute/virtualMachines| Update-AzTag -Tag $tags -Operation Merge
To add a new line between lines in an output you can use the `n character.
Write-Output "This is the first line. `nThis is the second line. `nThis is the third line"
Output
This is the first line.
This is the second line.
This is the third line
See also PowerShell New Line | How does new line methods work in PowerShell? (educba.com)
When working with custom objects in PowerShell, initializing an array of such objects might initially seem daunting. However, it's a straightforward process once you understand the syntax.
To initialize an array of custom objects, you can use the @()
syntax in conjunction with @{}
for each object within the array.
Here's a breakdown of the syntax:
$groups = @(
@{ Name = "First"; Property1 = Value1; Property2 = Value2 },
@{ Name = "Second"; Property1 = Value3; Property2 = Value4 },
# Add more objects as needed
)
In the above example:
$groups
is the variable storing the array of custom objects.@()
encapsulates the array.@{}
defines each custom object within the array.@{}
, you specify the properties and their respective values for each custom object.For instance, Name, Property1, and Property2 are properties of the custom objects, and you assign values to them accordingly.
By following this syntax, you can easily initialize an array of custom objects in PowerShell, making your scripts more efficient and readable.
To construct an array of objects in PowerShell, each item within the array is inherently treated as an object. Unlike conventional arrays that may consist of strings or integers, PowerShell arrays primarily contain objects. Below is a structured example demonstrating the creation of an array comprising objects through explicit declaration:
$people = @(
[PSCustomObject]@{Name='John'; Age=26},
[PSCustomObject]@{Name='Jane'; Age=22}
)
In this illustration, $people is an array variable containing two objects. Each object is defined using the [PSCustomObject] syntax followed by property-value pairs enclosed within curly braces {}. This structured approach ensures clarity and ease of comprehension while creating arrays of objects in PowerShell.
Using the *-Content
cmdlets. There are four *-Content
cmdlets:
Add-Content
– appends content to a file.Clear-Content
– removes all content of a file.Get-Content
– retrieves the content of a file.Set-Content
– writes new content which replaces the content in a file.The two cmdlets you use to send command or script output to a file are Set-Content and Add-Content. Both cmdlets convert the objects you pass in the pipeline to strings and then output these strings to the specified file. A very important point here – if you pass either cmdlet a non-string object, these cmdlets use each object’s ToString() method to convert the object to a string before outputting it to the file.
See more at How to send output to a file - PowerShell Community (microsoft.com)
Arrays are a fundamental feature of PowerShell. Arrays make it possible to ingest, manipulate and output true data structures (and not just raw strings). This capability makes PowerShell different and more useful than other scripting languages.
> Get-ExecutionPolicy
AllSigned
> Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine AllSigned
PowerShell is a powerful tool for managing system services, offering flexibility and control through straightforward commands. This guide covers the essentials of listing, searching, and managing services.
You often need administrative privileges to manage services. Running PowerShell as an administrator ensures you have the necessary permissions to start, stop, or modify services.
To see all the services on your system, use the Get-Service
cmdlet:
Get-Service
This outputs a list showing:
This command helps you get an overview of all services and their current state.