PowerShell by Julien

PowerShell Coding Samples


...see more

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.
  • Inside each @{}, 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.

...see more

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'
}
...see more

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"
}
...see more

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: $_"
}
...see more

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"}
...see more

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
...see more

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

...see more

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"
...see more

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

...see more

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)

...see more

Sometimes configuration files or scripts include identifiers that need to be updated automatically — for example, replacing a generic keyword like "rule-template" with a dynamic name based on a service or environment.

This Snipp shows how to:

  • Replace an exact identifier in a file
  • Normalize that name (e.g. replacing special characters like dots)

Goal

Replace this:

rule-template

With something like:

rule-example-service

Where "example.service" is the dynamic input.

PowerShell Example

# Define the original dynamic name
$name = "example.service"

# Normalize the name (e.g., replace '.' with '-')
$normalizedName = $name -replace '\.', '-'

# Read the text file content
$content = Get-Content -Path "file.txt" -Raw

# Replace the exact identifier
$content = $content -replace 'rule-template', "rule-$normalizedName"

# Save the updated content
Set-Content -Path "file.txt" -Value $content

This ensures that:

  • Only exact matches of "rule-template" are replaced
  • Any special characters in the name are safely converted

Summary

This method is useful when working with reusable config files across different services or environments. PowerShell makes it easy to normalize and apply names consistently, reducing manual edits and potential mistakes.

...see more

Need to quickly see the current date and time in your Windows terminal? This simple how-to guide shows you exactly which commands to use in both Command Prompt and PowerShell. It is useful for beginners, scripting, logging, and everyday tasks.

Step 1: Open the Terminal

  • Press Windows + R, type cmd, and press Enter for Command Prompt.
  • Or search for PowerShell in the Start menu.

Step 2: Show the Date and Time (Command Prompt)

Print only the date:

date /t

Print only the time:

time /t

Print both together:

echo %date% %time%

This is helpful when you want a quick timestamp in a script or log file.

Step 3: Show the Date and Time (PowerShell)

Display the current date and time:

Get-Date

Format the output:

Get-Date -Format "yyyy-MM-dd HH:mm:ss"

This creates a clean, readable timestamp like 2026-01-19 14:45:30.

💡 Tip

You can redirect these commands into a file to create simple logs.

Learning these small commands improves productivity and makes working in the Windows terminal easier and more efficient for daily tasks.

...see more

Have you ever run a command in PowerShell and wondered if it really worked or silently failed? Exit codes give you a simple way to know what happened. They are small numbers returned by a program when it finishes, and they tell you whether the task succeeded or not.

✔️ Exit Code 0 — Success
An exit code of 0 means everything worked as expected. The command or script completed without errors. This is the standard way most programs say, “All good.”

Exit Code 1 — Error
An exit code of 1 usually means something went wrong. It does not always tell you exactly what failed, but it signals that the command did not complete successfully. Different tools may use this code for different kinds of errors.

How to check the exit code in PowerShell
After running an external command, you can read the last exit code with:

$LASTEXITCODE

How to set your own exit code
In a script, you can control the result:

exit 0   # success
exit 1   # error

Understanding exit codes helps you automate tasks, detect problems early, and build more reliable scripts. Even beginners can use this small feature to make smarter decisions in their workflows.

Comments