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

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

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

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

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 References
  • Technologies
  • Testing
  • Visual Studio
  • Windows
 
Sets