PowerShell Coding Samples
Filter by Set

PowerShell Coding Samples

...see more

Checking if a string starts with some character (or a string) is a common need for every kind of PowerShell script. We can use PowerShell’s like operator with wildcard characters to check if a string starts with both case-sensitive and case-insensitive.

The following method is used to check if a string starts with another string using the like operator. By default like operator ignore the case-sensitive check.

$strVal ='Hello world'

if($strVal -like 'hello*') {
      Write-Host 'Your string is start with hello'
} else {
      Write-Host 'Your string does not start with hello"'

To perform a Case-Sensitive comparison just prefix the word “c” with the like operator (“clike”).

$strVal ='Hello world'

if($strVal -clike 'Hello*') {
      Write-Host 'True'
} else {
      Write-Host 'False'
}
...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

If we want to only get the first line of a file we can use the Get-Content cmdlet and pipe this to the Select-Object cmdlet and use the First parameter to retrieve one line.

Get-Content -Path "C:\file.txt" | Select-Object -First 1

Alternatively, this could also be done on an object

$content = Get-Content -Path "C:\file.txt"
...
$firstLine = Get-Content $content | Select-Object -First 1
...see more

How To Write PowerShell Output To A Text File And Overwrite It

There are three ways to overwrite the content of a text file. Firstly, if you run the Out-File command without the Append parameter, it will overwrite the content of the text file.

Moreover, you can overwrite the content of a text file with the Set-Content command. Finally, you can use the > redirection operator to overwrite the content of a text.

"does out-file overwrite - line 1" | Out-File -FilePath C:\overwrite.txt
"does out-file overwrite - line 2" > C:\overwrite.txt
"does out-file overwrite - line 3" | Set-Content C:\overwrite.txt
Set-Content C:\overwrite.txt -Value "does out-file overwrite - line 4"

Append to file

"does append - line 1" | Out-File -FilePath C:\append.txt -Append
"does append - line 2" >> C:\append.txt
Add-Content -Path C:\append.txt -Value "does append - line 3"
...see more

Given a CSV file with some comments on the first line and starting with the headers on the second line. The Import-Csv cmdlet will not work in this scenario. In this case, you need to skip the first line to recognize the headers.

You need to get the file and then use the Select-Object cmdlet with the Skip parameter to skip the first line and then convert this to CSV.

In this sample, we then use the ConvertFrom-Csv cmdlet to convert into CSV format.

$csvFile = 'file.csv'
$csvData = Get-Content -Path $csvFile | Select-Object -Skip 1 | ConvertFrom-Csv
...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

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

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

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)

Add to Set
  • .NET 6.0 Migration
  • 5 Best websites to read books online free with no downloads
  • 5 surprising things that men find unattractive
  • 5 Ways To Take Control of Overthinking
  • 6 simple methods for a more productive workday
  • 6 Ways To Stop Stressing About Things You Can't Control
  • Add React to ASP.NET Core
  • Adding reCAPTCHA to a .NET Core Web Site
  • Admin Accounts
  • Adobe Acrobat
  • Afraid of the new job? 7 positive tips against negative feelings
  • Agile
  • AI
  • AKS and Kubernetes Commands (kubectl)
  • API Lifecycle Management
  • Application Insights
  • arc42
  • Architectures
  • Article Writing Tools
  • ASP.NET Core Code Snippets
  • ASP.NET Core Performance Best Practices
  • ASP.NET Core Razor Pages
  • ASP.NET: Razor Syntax Cheat Sheet
  • Atlassian
  • Azure
  • Azure API Management
  • Azure App Registration
  • Azure Application Gateway
  • Azure Arc
  • Azure Arc Commands
  • Azure Architectures
  • Azure Bastion
  • Azure Bicep
  • Azure CLI Commands
  • Azure Cloud Products
  • Azure Cognitive Services
  • Azure Container Apps
  • Azure Cosmos DB
  • Azure Cosmos DB Commands
  • Azure Costs
  • Azure Daily
  • Azure Daily 2022
  • Azure Daily 2023
  • Azure Data Factory
  • Azure Database for MySQL
  • Azure Database for PostgreSQL
  • Azure Databricks
  • Azure Diagram Samples
  • Azure Durable Functions
  • Azure Firewall
  • Azure Functions
  • Azure Kubernetes Service (AKS)
  • Azure Landing Zone
  • Azure Log Analytics
  • Azure Logic Apps
  • Azure Maps
  • Azure Monitor
  • Azure News
  • Azure PowerShell Cmdlets
  • Azure PowerShell Login
  • Azure Private Link
  • Azure Purview
  • Azure Redis Cache
  • Azure Security Groups
  • Azure Sentinel
  • Azure Service Bus
  • Azure Service Bus Questions (FAQ)
  • Azure Services Abstract
  • Azure SQL
  • Azure Storage Account
  • Azure Tips and Tricks
  • Backlog Items
  • BASH Programming
  • Best LinkedIn Tips (Demo Test)
  • Best Practices for RESTful API
  • Bing Maps
  • Birthday Gift Ideas for Wife
  • Birthday Poems
  • Black Backgrounds and Wallpapers
  • Bootstrap Templates
  • Brave New World
  • Break Out of a JavaScript Loop
  • Brian Tracy Quotes
  • Build Websites Resources
  • C# Code Samples
  • C# Design Patterns
  • C# Development Issues
  • C# Programming Guide
  • Caching
  • Caching Patterns
  • Camping Trip Checklist
  • Canary Deployment
  • Careers of the Future You Should Know About
  • Cheap Vacation Ideas
  • Cloud Computing
  • Cloud Migration Methods
  • Cloud Native Applications
  • Cloud Service Models
  • Cloudflare
  • Code Snippets
  • Collection in JavaScript
  • Compelling Reasons Why Money Can’t Buy Happiness
  • Conditional Access
  • Configurations for Application Insights
  • Const in JavaScript
  • Create a Routine
  • Create sitemap.xml in ASP.NET Core
  • Creative Writing: Exercises for creative texts
  • CSS Selectors Cheat Sheet
  • Cultivate a Growth Mindset
  • Cultivate a Growth Mindset by Stealing From Silicon Valley
  • Custom Script Extension for Windows
  • Daily Scrum (Meeting)
  • Dalai Lama Quotes
  • Data Generators
  • DataGridView
  • Decision Trees
  • Deployments in Azure
  • Dev Box
  • Develop ASP.NET Core with React
  • Development Flows
  • Docker
  • Don’t End a Meeting Without Doing These 3 Things
  • Drink More Water: This is How it Works
  • Dropdown Filter
  • Earl Nightingale Quotes
  • Easy Steps Towards Energy Efficiency
  • Elon Musk
  • Elon Musk Companies
  • Employment
  • English
  • Entity Framework Core: Syntax and Commands
  • Escape Double Quotes in C#
  • Escaping characters in C#
  • Executing Raw SQL Queries using Entity Framework Core
  • Factors to Consider While Selecting the Best Earthmoving System
  • Feng Shui 101: How to Harmonize Your Home in the New Year
  • Flying Machines
  • Foods against cravings
  • Foods that cool you from the inside
  • Four Misconceptions About Drinking
  • Fox News
  • Free APIs
  • Funny Life Quotes
  • Generate Faces
  • Generate Random Numbers in C#
  • Genius Money Hacks for Massive Savings
  • Git
  • Git Cheat Sheet
  • Git for Beginners
  • Git Fork
  • GitHub
  • GitHub Concepts
  • Green Careers Set to Grow in the Next Decade
  • Habits Of Highly Stressed People and how to avoid them
  • Happy Birthday Wishes & Quotes
  • Helm Overview
  • How to Clean Floors – Tips & Tricks
  • How to invest during the 2021 pandemic
  • How To Make Money From Real Estate
  • How To Stop Drinking Coffee
  • HTTP Status Code
  • Image for Websites
  • Inspirational Quotes
  • Iqra Technology, IT Services provider Company
  • JavaScript
  • JavaScript Scope
  • JavaScript Snippets
  • JavaScript Var, Let, and Const
  • Jobs Of 2050
  • jQuery
  • jQuery plugins
  • JSON (JavaScript Object Notation)
  • JSON for Linking Data (JSON-LD)
  • Json to C# Converters
  • JSON Tree Viewer JavaScript Plugin
  • JSX (ReactJS)
  • Karen Lamb Quotes
  • Kubernetes Objects
  • Kubernetes Tools
  • Kusto Query Language
  • Lack of time at work? 5 simple tricks to help you avoid stress
  • Lambda (C#)
  • Last Minute Travel Tips
  • Last-Minute-Reisetipps
  • Latest Robotics
  • Leadership
  • Let in JavaScript
  • List Of Hobbies And Interests
  • Logitech BRIO Webcam
  • Management
  • Mark Twain Quotes
  • Markdown
  • Meet Sophia
  • Message-Oriented Architecture
  • Microservices
  • Microsoft Authenticator App
  • Microsoft Power Automate
  • Microsoft SQL Server
  • Microsoft Teams
  • Mobile UI Frameworks
  • Motivation
  • Multilingual Applications
  • NBC News
  • NuGet
  • OAuth Authentication Flows
  • Objectives and Key Results (OKR)
  • Objectives and Key Results (OKR) Samples
  • OKR Software
  • Online JSON Viewer and Parser
  • Outlook Automation
  • PCMag
  • Phases of any relationship
  • Playwright
  • Popular cars per decade
  • Popular Quotes
  • PowerShell
  • PowerShell Array Guide
  • PowerShell Cmdlets
  • PowerShell Coding Samples
  • PowerToys
  • Prism
  • Pros & Cons Of Alternative Energy
  • Quill Rich Text Editor
  • Quotes
  • RACI Matrix
  • Razor Syntax
  • Reasons why singletasking is better than multitasking
  • Regular Expression (RegEx)
  • Reorder List in JavaScript
  • Resize Images in C#
  • Response Caching in ASP.NET Core
  • RESTful APIs
  • Rich Text Editors
  • Rob Siltanen Quotes
  • Robots
  • Run sudo commands
  • Salesforce Offshore Support Services Providers
  • Sample Data
  • Save Money On Food
  • Score with authenticity in the job interview
  • Scrum
  • Scrum Meetings
  • Security
  • Semantic Versioning
  • Serialization using Thread Synchronization
  • Service Worker
  • Speak and Presentation
  • SQL Functions
  • SQL References
  • SQL Server Full-Text Search
  • Successful
  • Surface Lineup 2021
  • Surface Lineup 2021 Videos
  • SVG Online Editors
  • Team Manifesto
  • Technologies
  • Technology Abbreviations
  • Technology Glossary
  • TechSpot
  • That is why you should drink cucumber water every day
  • The Cache Tag Helper in ASP.NET Core
  • The Verge
  • Theodore Roosevelt Quotes
  • These 7 things make you unattractive
  • Things Successful People Do That Others Don’t
  • Things to Consider for a Great Birthday Party
  • Things to Consider When Designing A Website
  • Thoughts
  • TinyMCE Image Options
  • TinyMCE Toolbar Options
  • Tips for a Joyful Life
  • Tips for fewer emails at work
  • Tips for Making Better Decisions
  • Tips for Managing the Stress of Working at Home
  • Tips for Writing that Great Blog Post
  • Tips On Giving Flowers As Gifts
  • Tips you will listen better
  • Top Fitness Tips
  • Top Healthy Tips
  • Top Money Tips
  • Top Ten Jobs
  • Track Authenticated Users in Application Insights
  • Unicode Characters
  • Var in JavaScript
  • Visual Studio 2022
  • Vital everyday work: tips for healthy work
  • Walking barefoot strengthens your immune system
  • Walt Disney Quotes
  • Ways for Kids to Make Money
  • Web Design Trends & Ideas
  • Web Icons
  • Web Scraping
  • Webhooks
  • Website Feature Development
  • What are my options for investing money?
  • What happens when you drink water in the morning
  • What Is Stressful About Working at Home
  • What To Eat For Lunch
  • Windows
  • Windows 11 Top Features You Should Know
  • Winston Churchill Quotes
  • XPath
  • You'll burn out your team with these 5 leadership mistakes
  • ZDNet
 
Sets