PowerShell
...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.

...see more

Calling web services is common in automation, monitoring, and integration tasks. Many APIs expect extra information in the request, such as authentication tokens, data formats, or custom settings. This information is sent through headers. Once you understand how headers work in PowerShell, you can safely connect to most modern services and build reliable scripts with confidence.

Why Headers Matter

Headers describe how the server should handle your request. They can:

  • Identify who you are (authentication)
  • Tell the server what data format you send or expect
  • Enable special features or versions of an API

Without the correct headers, a request may fail or return unexpected data.

How PowerShell Handles Headers

PowerShell uses a simple key-value structure called a hashtable. Each key is the header name, and the value is the header content. This hashtable is passed to the request using the -Headers parameter.

Example: Add One Header

$headers = @{
    "Authorization" = "Bearer YOUR_TOKEN"
}

Invoke-RestMethod -Uri "https://api.example.com/data" -Headers $headers

Example: Add Multiple Headers

$headers = @{
    "Authorization" = "Bearer YOUR_TOKEN"
    "Content-Type"  = "application/json"
    "Accept"        = "application/json"
}

Invoke-RestMethod -Uri "https://api.example.com/data" -Method Get -Headers $headers

Example: Send Data with Headers (POST)

$headers = @{
    "Content-Type" = "application/json"
}

$body = @{
    name = "Sample"
    value = 123
} | ConvertTo-Json

Invoke-RestMethod -Uri "https://api.example.com/items" -Method Post -Headers $headers -Body $body

Key Takeaway

Create a hashtable for headers and attach it using -Headers. This approach works for most APIs and keeps your scripts clean, readable, and easy to maintain.

 

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

Retrieving data from a URL or calling a web API is one of the most common PowerShell tasks. Whether you want to check a website’s status, download a file, or interact with a REST API, PowerShell provides built-in commands for this purpose.

1. Using Invoke-WebRequest

Invoke-WebRequest is used to fetch web pages or files.
Example:

$response = Invoke-WebRequest -Uri "https://example.com"
$response.Content

This command returns the full HTTP response, including status code, headers, and body content.

To download a file:

Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "C:\Temp\file.zip"

2. Calling APIs with Invoke-RestMethod

For APIs that return JSON or XML, Invoke-RestMethod is the better choice. It automatically converts the response into PowerShell objects:

$data = Invoke-RestMethod -Uri "https://api.github.com"
$data.current_user_url

You can also send POST requests:

Invoke-RestMethod -Uri "https://api.example.com/data" -Method POST -Body '{"name":"John"}' -ContentType "application/json"

3. Running PowerShell from the Command Line

PowerShell commands can be executed directly from the traditional Windows Command Prompt:

powershell -Command "Invoke-WebRequest -Uri 'https://example.com'"

Or, if available, using curl:

curl https://example.com

Summary

With just a few commands, PowerShell becomes a versatile tool for web requests and API communication — ideal for automation, system monitoring, or accessing online data sources.

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

To display JSON in a structured and readable format directly in PowerShell, you can pipe a JSON string through ConvertFrom-Json and then ConvertTo-Json with an appropriate -Depth parameter. This allows you to avoid using intermediary variables and outputs neatly formatted JSON directly to the console.

Example:

'{"name":"John","age":30,"address":{"street":"123 Main St","city":"Anytown"},"phones":["123-4567","987-6543"]}' 
| ConvertFrom-Json 
| ConvertTo-Json -Depth 10

Explanation:

  • ConvertFrom-Json parses the raw JSON string into a PowerShell object.
  • ConvertTo-Json re-serializes the object with proper indentation.
  • The -Depth parameter ensures that nested objects are fully expanded in the output.

This approach is useful for quickly inspecting JSON structures without needing temporary variables or additional tools.

...see more

The msDS-UserPasswordExpiryTimeComputed attribute in Active Directory stores the user’s password expiration time as a large integer in Windows FileTime format. This format counts 100-nanosecond intervals from January 1, 1601 (UTC). To get a readable date and time, you must convert this number to a standard datetime format using the appropriate method for your platform.

How to Convert:

  • Use built-in functions like FromFileTimeUtc in PowerShell or .NET.
  • In Python, add the FileTime interval (converted to microseconds) to the epoch starting at 1601-01-01.

Example in PowerShell:

[DateTime]::FromFileTimeUtc($filetimeValue)

Handling the Special “Magic” Number:
If the value equals 9223372036854775807 (the maximum 64-bit integer), it is a special indicator that the password never expires. This number is not a real timestamp and should not be converted to a date. Instead, treat it as a flag meaning “no expiration.”

Summary:

  • Convert valid FileTime values to datetime for expiry information.
  • Recognize 9223372036854775807 as a sentinel meaning “password never expires.” Avoid converting this sentinel to a datetime.
...see more

This solution demonstrates how to retrieve the password expiration date of a user account in Active Directory using PowerShell. It uses the Get-ADUser cmdlet from the Active Directory module and queries the msDS-UserPasswordExpiryTimeComputed property, which holds the computed expiration date in FILETIME format.

If querying by -Identity returns an error such as "Cannot find an object with identity," switching to a -Filter approach with the SamAccountName is recommended. Also, ensure that the Active Directory module is imported, the domain context is correct, and the executing user has appropriate permissions.

# Import the Active Directory module if not already loaded
Import-Module ActiveDirectory

# Replace 'username' with the actual SamAccountName of the user
$user = Get-ADUser -Filter {SamAccountName -eq "username"} -Properties msDS-UserPasswordExpiryTimeComputed

# Convert the FILETIME to a readable DateTime object
$passwordExpiry = if ($user."msDS-UserPasswordExpiryTimeComputed") {
    [datetime]::FromFileTime($user."msDS-UserPasswordExpiryTimeComputed")
} else {
    "Password does not expire or no expiration set."
}

# Output the result
[PSCustomObject]@{
    UserName       = $user.SamAccountName
    PasswordExpiry = $passwordExpiry
}

Key Points:

  • Use -Filter with SamAccountName to avoid identity resolution issues.
  • The property msDS-UserPasswordExpiryTimeComputed returns the expiration time as FILETIME.
  • Convert FILETIME to DateTime for human-readable output.
  • Confirm the environment context and permissions to avoid access errors.
...see more

To see all the services on your system, use the Get-Service cmdlet:

Get-Service
 

This outputs a list showing:

  • Name: The internal service name.
  • DisplayName: A user-friendly name.
  • Status: Indicates whether the service is running, stopped, or paused.

This command helps you get an overview of all services and their current state.

...see more

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.

Steps:

  1. Right-click the PowerShell icon.
  2. Select Run as Administrator.
  3. Confirm the User Account Control (UAC) prompt, if it appears.
...see more

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.

...see more

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.

...see more

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.

...see more

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

...see more

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)

...see more

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.

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

Add to Set
  • .NET
  • Agile
  • AI
  • ASP.NET Core
  • Azure
  • C#
  • Cloud Computing
  • CSS
  • EF Core
  • HTML
  • JavaScript
  • Microsoft Entra
  • PowerShell
  • Quotes
  • React
  • Security
  • Software Development
  • SQL
  • Technology
  • Testing
  • Visual Studio
  • Windows
Actions
 
Sets