
Merry Christmas to all! Here is a blog specifically targeted towards beginners that are interested in learning how to write scripts in Powershell.
This blog post is creating an Azure DevOps library group via Powershell. I like to use the library group feature within Azure DevOps but there is one big downside. The library group doesn’t have version history. When someone in your team makes a change to the library group, the previous version is not available,
So, how can we solve this issue? Exactly, create the library group via Powershell/Rest API. If we store this code in a git repository, we have version history and can use the feature just like all the other features within Azure DevOps. I got this idea from Patrick van den Born, check out his blog also!
The first blog only features the creation of the library group itself. I will dedicate another to creating the variables.
Let’s Get Started…
White top section: Where we will write our script
Blue section: A ‘dummy’ terminal we can use when creating our script
Right side: Command Add-on (I usually exit this out immediately)
It might look a little daunting at first, with all of the commandlets on the right side of your screen. PowerShell calls all of its’ functions commandlets by the way, or cmdlets for short. The layout of a cmdlet is <verb>-<noun>. An example of this is Get-NetAdapter. If you wanted to write your own functions, which we will explore later in this blog post, you can name the function whatever you want — — or you can be fancy and only use ‘approved verbs’ which can be viewed by executing Get-Verb. It is a better practice to use approved verbs when writing/sharing your custom functions, for the sake of normalization.

The -like operator in PowerShell provides a simple way to perform string matching and filtering. While you can use the -eq and -contains operators for basic string matching, the -like operator offers more flexible and powerful wildcard pattern matching capabilities. In this comprehensive guide, we will explore everything you need to know about like in PowerShell, including its syntax, operators, and advanced usage of -like to find text patterns in strings and filter collection objects.
We’ll also cover the wildcard in a switch statement, using -like and -notlike to filter collections, combining -like with other logical operators, and more through easy-to-understand examples. By the end of this guide, you will be able to master the PowerShell like and improve your PowerShell skills. Let’s get started mastering the -like operator in PowerShell!
Introduction to PowerShell -Like Operator
In this syntax, $string is the string that you want to compare, and "pattern" is the pattern that you want to match against the string. The pattern can include wildcard characters, such as * and ?, which allows you to match multiple characters or single characters, respectively.
This command will return True, as the string “Hello” starts with the letter “H”.
For a single-character match, you’d use ?.
Here are some common -like patterns:
He*– Begins with “He”*Hello– Ends with “Hello”*text*– Contains “text” anywhereH?llo– Matches one character between “H” and “llo”
This makes -like very flexible for pattern matching in strings.
Making -like Case-sensitive
The like operator in PowerShell performs case-insensitive comparison by default, meaning it will match strings regardless of their case. However, you can use the -clike operator to perform a case-sensitive comparison.
The -clike parameter is the case-sensitive version. This matches “Hello” to “h*”.
I’m trying to create a Powershell script that looks for just files with the extension .dgn within a specific directory. Then if it has a character string of “_ch_” in the name of the file it will delete it. Else it will move the file to a new directory.
Function Remove-ExtraneousCADFiles { [CmdletBinding()] Param ( [Parameter(ValueFromPipeline = $true)] $paths ) Begin {Clear-Host} Process { $char = "_ch_" $fileName = Split-Path $input -leaf $destDir = "D:\CRASH\ACCID - Lite Test\" Write-Output ("fileName= " + $fileName) Write-Output ("char= " + $char) Write-Output ("_.Name= " + $_.Name) #if ($_.contains($char)) { #if (Where $_.Name -Match $char) { #if ($_.Name -Match $char) { if ($_.Name -Like $char) { Remove-Item $_ -Force -Confirm -WhatIf Write-Output ("Delete= " + $fileName.Name) } else { #Write-Output ("Move _.FullName= " + $_.FullName) #Write-Output ("destDir= " + $destDir) #Write-Output ("_.BaseName= " + $_.BaseName) #Write-Output ("_.Extension= " + $_.Extension) #Write-Output "" Move-Item -Path $_.FullName -Destination ($destDir + $_.BaseName + $_.Extension) -WhatIf Write-Output "" } } End {} }
$inputPath = "D:\CRASH\ACCID - Lite Test zzz"
(Get-ChildItem -Path $inputPath -Recurse -Include *.dgn) | Remove-ExtraneousCADFilesBut I can’t get the “IF” portion of my script to pass anything to the Remove-Item or Write-Output command. I’ve try other commands but I’m not having any luck, any help would be greatly appreciated.
These are an example of the files I’m trying to weed out to either delete or move:

67 gold badges673 silver badges862 bronze badges
asked Sep 15, 2023 at 18:27
$_.Name -Like $char
-like uses wildcard expressions, which must match the input as a whole.
$_.Name -like "*$char*"Alternatively use -match, which matches part of the input by default (substring matching):
$_.Name -match $charHowever, note that -match uses regular expressions (regexes), so if your – designed to be used verbatim – search string happens to contain regex metacharacters (e.g., ., +), you’ll have to escape them (not necessary in your case):
$_.Name -match [regex]::Escape($char)- That is,
$_.Name.Contains($char)does work for case-exact matching.
- That is,
However, this is at odds with PowerShell’s fundamentally case-insensitive nature:
invariably so in Windows PowerShell: there is no overload with a case-insensitivity opt-in.
in PowerShell (Core) 7+ you can use a newly introduced overload of
.Contains()that permits case-insensitive matching on an opt-in basis, via an additional parameter, e.g.:# PowerShell (Core) v7+ only 'foo'.Contains('OO', 'InvariantCultureIgnoreCase') # -> $true
While direct use of .NET APIs is a viable option – which is a testament to PowerShell’s versatility – the flip side is that doing so is not PowerShell-idiomatic, for two reasons:
By default, .NET APIs are case-sensitive , whereas PowerShell is case-insensitive.
Calling .NET APIs:
answered Sep 15, 2023 at 19:30
67 gold badges673 silver badges862 bronze badges
Back to Misc
Load the Powershell module
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn Add-PSSnapIn -Name Microsoft.Exchange, Microsoft.Windows.AD
Restart DAG server
Move-ActiveMailboxDatabase –Server ToBeRebootedServer Get-MailboxDatabaseCopyStatus *
Restart single server
Get-service | ?{$_.Name -ilike "MSexch*"} | stop-serviceGet-ADUser -Identity sp13_admin -Properties LastLogon | Select Name, @{Name='LastLogon';Expression={[DateTime]::FromFileTime($_.LastLogon)}}Get-Mailbox -identity “MailboxName” | fl
Get-Mailbox | Select DisplayName, SamAccountName, UserPrincipalName, PrimarySMTPAddress
Get-MailboxStatistics -Database (DM) | Select DisplayName, TotalItemSize
Get-Mailbox | Where-Object {$_.displayname -like ‘*User*Name*‘} | fl
Get-MailboxStatistics -Filter ‘displayName -eq “NameOfMailbox“‘ | flGet-ExchangeServer | fl Get-MailboxDatabase | fl Get-MailboxDatabase -Identity “MailboxDatabase” -Server “Server” -Status | Format-List
Open remote connection to Exchange server
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ExchangeServer/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $SessionOr for Office 365 use this -ConnectionUri instead:
https://outlook.office365.com/powershell-liveid/ -Authentication Basic -Credential $UserCredential -SessionOption $ProxyOptionsDisplay “Full Access” Permissions for a Mailbox
Get-MailboxPermission John | Where { ($_.IsInherited -eq $False) -and -not ($_.User -like “NT AUTHORITY\SELF”) } | Select Identity,user,AccessRightsAdd calendar permissions:
Add-MailboxFolderPermission -Identity “MailboxName:\Calendar” -User UserRequiringAccess -AccessRights Reviewer
Assign “Full Access” permissions for a Mailbox
Add-MailboxPermission John -User Suzan -AccessRights FullAccess -InheritanceType All
Assign “Send As” Permissions for a Mailbox
Add-RecipientPermission John -AccessRights SendAs -Trustee Suzan
Assign “Send As” Permissions for recipient for each member in a distribution group
$DL = Get-DistributionGroupMember DL-01
Foreach ($item in $DL) { Add-RecipientPermission $item.name -AccessRights SendAs –Trustee Suzan }Sets email forwarding on mailbox:
Set-Mailbox -Identity “MailboxName” -ForwardingAddress “[email protected]” -DeliverToMailboxAndForward $trueRevoke “Full Access” Permissions
Remove-MailboxPermission John -User Suzan -AccessRights FullAccess
Get-MigrationUser -BatchId StagedBatch1 | Get-MigrationUserStatistics
Message Tracking log
Get-MessageTrackingLog -Start "02/26/2018 08:23:00" -End "02/28/2018 17:00:00" -Recipients $recipientSMTP -Server $ExchServer
Set-MailboxAutoReplyConfiguration -Identity "Desmond Miles" -AutoReplyState Enabled ` -InternalMessage "I'm currently on leave until 23th April. Please contact Ezio Auditore on x72023 for urgent matters." AutoReplyState can also be: AutoReplyState Scheduled –StartTime “02/28/2018 07:00:00” –EndTime 03/18/2018 17:00:00
Export Mailbox to PST
New-MailboxExportRequest -Mailbox User01 -FilePath ‘\\SERVER01\PSTFileShare\User01_Recovered.pst’
New-MsolUser -UserPrincipalName "[email protected]" -DisplayName " Desmond Miles " -FirstName "Desmond" -LastName "Miles" -UsageLocation "CH" -LicenseAssignment "Contoso:BPOS_Standard"
New-MsolUser -DisplayName <DisplayName> -FirstName <FirstName> -LastName <LastName>
-UserPrincipalName <Account> -UsageLocation <CountryCode> -LicenseAssignment <AccountSkuID> [-Password <Password>]UserPrincipalName,FirstName,LastName,DisplayName,UsageLocation,AccountSkuId[email protected],Claude,Loiselle,Claude Loiselle,US,contoso:ENTERPRISEPACK[email protected],Lynne,Baxter,Lynne Baxter,US,contoso:ENTERPRISEPACK[email protected],Shawn,Melendez,Shawn Melendez,US,contoso:ENTERPRISEPACK
Import-Csv -Path <Input CSV File Path and Name> |
foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName
-UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuId [-Password $_.Password]}
| Export-Csv -Path <Output CSV File Path and Name>Office 365 commands:
https://blog.netwrix.com/2018/09/19/ten-most-useful-office-365-powershell-commands/How To Troubleshoot
I originally made a mistake in my .csv output example. When trying to output to .csv here is what my code first looked like (I’ll highlight the missing section in comparison to the above):
Problem: The output shows a bunch of blank spaces in the .csv file. This is because we didn’t include the ‘if True’ logic explained above. Our code told Windows to write every instance of $PII to our $Finalobject, regardless if there were any matching patterns found.
For example, I used write-host to understand the output of the $PII variable:
In the output we get all of those blank spaces, so now we know the issue isn’t necessarily with ‘Export-CSV’ but how we are fetching that $PII variable and appending it to our $FinalObject.
So logically speaking, we need to tell PowerShell to only add the content that actually returns True as opposed to adding every single $PII instance
Voila! We can now see there are no additional spaces in our output and our csv will look proper.
The exclamation ‘!’ point before our $PII variable essentially tells Powershell to look for ‘if NOT <condition>’. If this false condition is met, we will write $PII and ‘this is false’ to our terminal. This is what our pseudo debugging output looks like:
Conclusion: We have finished our goal scenario and created a report of all instances of PII data (specifically DOB and SSN).
Combining Like Operator with Logical -And, -Or, -Not Operators
PowerShell -like operator can be combined with logical operators like -and , -or, and -Not for multiple comparisons. This combination is commonly used in PowerShell scripts and commands to perform complex string comparisons.
$string -like "pattern1" -or $string -like "pattern2"
In this syntax, $string is the string that you want to compare and "pattern1" and "pattern2" are the patterns that you want to match against the string. The -like operator is used to perform the string comparisons, and the -or operator is used to combine them using the OR condition. E.g.,
$string -like "Hello" -and $string -notlike "Bye"
$string = "Apple"
if ($string -like "A*" -or $string -like "*B") { Write-Host "The string starts with A or ends with B"
}This command will output the message “The string starts with A or ends with B”, as the string “Apple” starts with the letter “A”. Similarly, the AND logical operator can be used as:
$strings = @("PowerA", "PowerB", "MagicA", "MagicB")
$strings | Where-Object { $_ -like "Power*" -and $_ -like "*A" }This Returns “PowerA”. We can also negate the entire statement with -not:
-not ($string -like "Hi" -or $string -like "Hello")
PowerShell String -Like Examples
Let’s look at some examples to help you understand how the PowerShell -like works in practice.
Example 1: Matching a specific string
You can use it for comparing entire strings:
$string = "Hello, world!"
if ($string -like "Hello, world!") { Write-Host "The string matches"
}This command will output the message “The string matches”.
Example 2: Matching a pattern using wildcards
$productCodes = @("CAT45123", "DOG56789", "CAT45234", "FISH98765")
$productCodes | Where-Object { $_ -like "CAT45*" }This command will output CAT45123, CAT45234.
$emails = @("john@example.com", "alice@gmail.com", "bob@example.com")
$emails | Where-Object { $_ -like "*@example.com" }You want to get all lines from a log file where an error or warning is logged:
Get-Content C:\Temp\AppLog.txt | Where-Object { $_ -like "*ERROR*" -or $_ -like "*warning*" }Example 3: Filter Files using NotLike Operator
Let’s filter files by specific type using NotLike:
Get-ChildItem -Path C:\Images -File | Where-Object { $_.Name -notlike "*.jpg" -and $_.Name -notlike "*.png" }This filters out all the JPG and PNG files.
Example 4: Single Character Pattern Matching
$EmployeeNumber = "Emp-456-7890"
if ($EmployeeNumber -like "???-???-????") { Write-Host "The string matches the Employee number pattern"
}This command will output the message “The string matches the Employee number pattern”, as the string matches the pattern for an employee number. Here, each ? matches any single character. This will match any string that fits the format of three characters, a hyphen, three more characters, another hyphen, and then four characters.
What are some real-world examples of what can be accomplished using PowerShell?
- Automating deployment or provisioning of systems
- Automating user configuration management
- Systems management
- Auditing
- Log analysis
- Hacking
- The limit does not exist
Useful link to consider:
Powershell MSDocs: https://learn.microsoft.com/en-us/powershell/
Preparation

Click on New Token:

Name the token and pick an expiration date:

Note: I have picked full access. Don’t do this in production.
Click on Create and save the token to a preferred method.
Next, we need to identify the Azure DevOps project ID which we want to create the library group for.
You can do so by using this code snippet:
$ADO_PAT = Read-Host -Prompt "Enter your ADO PAT"
$EncodedPAT = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$ADO_PAT"))
$headers = @{Authorization = "Basic $EncodedPAT" }
(Invoke-RestMethod -Method 'GET' -Uri "https://dev.azure.com/ORGANIZATIONNAME/_apis/projects?api-version=5.0-preview.3" -Headers $headers).valueNOTE: Change the ORGANIZATIONNAME in the URI.
Run the script, it will first ask you for the Personal Access Token created in the first step:

Save the ID to a notepad of some sort, we need this to create the group.
Firstly, save this script as a ps1 file:
[CmdletBinding()]
param ( [Parameter()][string]$ADO_Organization, [Parameter()][string]$ADO_Project, [Parameter()][string]$ADO_Project_Id, [Parameter()][string]$ADO_VariableGroup_Name, [Parameter()][string]$ADO_PAT
)
$EncodedPAT = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$ADO_PAT"))
$headers = @{Authorization = "Basic $EncodedPAT" }
$Uri = "https://dev.azure.com/$($ADO_Organization)/$($ADO_Project)/_apis/distributedtask/variablegroups?api-version=7.0"
$Json = @"
{ "name": "$ADO_VariableGroup_Name", "type": "Vsts", "variables": { "ManagedByAzureDevOps": { "value": "DontChangeValuesHere" } }, "variableGroupProjectReferences": [ { "name" : "$ADO_VariableGroup_Name", "description" : "This group is managed via Code, dont changed the values", "projectReference": { "id":"$($ADO_Project_Id)", "name": "$($ADO_Project)" } } ]
}
"@
try { Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $headers -Body $Json -ContentType 'application/json'
}
catch { Write-Error "Error creating ADO variable group" Write-Error $_.Exception.Message
}After that, use this code snippet to run the file:
$ADO_PAT = Read-Host -Prompt "Enter your ADO PAT" $ADO_Organization = "nielskoktech" $ADO_Project = "nielskoktech" $ADO_Project_Id = "YOUR PROJECT ID FROM STEP 2" $ADO_VariableGroup_Name = "NielsKokTechExample" .\NielsKokTechTest\AzureDevOps\CreateLibraryGroup.ps1 -ADO_Organization $ADO_Organization ` -ADO_Project $ADO_Project ` -ADO_PAT $ADO_PAT ` -ADO_VariableGroup_Name $ADO_VariableGroup_Name ` -ADO_Project_Id $ADO_Project_Id
As a result, the group is created:



Step 2 — Generating a Report
The final part of our task is to write these results to some sort of output file since that’s what our scenario demands. I’ll write two solutions — one for outputting to a .txt file, and the other for outputting to a .csv file. Some scenarios require different types of output, and generating a clean report is better done in .csv than .txt for management’s sake.
Here is code to output to a .txt file:
All in one-line, we recursively listed all contents of each folder, piped it to select-string and specified which patterns we are looking for, and then redirected the output to a .txt file using the ‘>>’ operator. We can use this to redirect our memory stream to a file. As summarized by Microsoft:
There is also the write-output or out-file cmdlets we could use, but the code looks a little bit different.
Anyhow, what if our job requires a .csv file as output? In order for this to look pretty, this takes a bit more code than redirecting output in PowerShell — here is what that would look like:
Output to .csv file:
Output (shown in LibreOffice):
We define an empty object called $FinalObject, we’re going to use this later as an object that we append things to. We then will pipe this object to a cmdlet called export-csv which writes csv files. We then save our get-childitem output into an $Allitems variable. We create a foreach loop, with a random name $Singleitem as the variable we will use for each individual file. We create a $PII variable and save the select-string output into this. We then tell the code if this variable is True to append each instance to our previously empty $Finalobject object, and create the properties we will use for our CSV columns. In this case we created one called Filename and one called PII. Finally, we take this $Finalobject and pipe it to select-object, specify our properties, pipe to sort-object so we can sort it by whichever properties we specify, and we pipe that to the Export-CSV cmdlet with an output path/filename as well as a parameter -NoTypeInformation for prettier output.
First off, what is PowerShell?
An object-oriented scripting language used primarily for Windows automation/configuration management. As Microsoft states, “PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework. PowerShell runs on Windows, Linux, and macOS.”
PowerShell Where Like – Filter and Search Strings
With PowerShell’s pipeline capability, You can combine the Where-Object to filter arrays or collections using -like. This command is commonly used in PowerShell scripts and commands to filter and search for specific strings in a collection of files, folders, or other objects.
$collection | where { $_.Property -like "pattern" }In this syntax, $collection is the collection of objects that you want to filter, and "pattern" is the pattern you want to match against the specified property of each object in the collection. The -like operator is used to perform the string comparison.
Filtering Arrays with Where-Object:
A common use case for -like is to filter a collection of strings, E.g.,
$values = @("PowerShell", "PowerPoint", "PowerApps","Photoshop")
$pattern= "Power*"
$values | Where-Object { $_ -like $pattern }This would return “PowerShell”, “PowerPoint”, and “PowerApps” because they begin with “Power”.
PowerShell PowerPoint PowerApps
Here is another example:
$Files = "file1.txt","file2.csv","photo.jpg" TextFiles = $files -like "*.txt"
Get-ChildItem | where { $_.Name -like "*report*" }This command will return a collection of file objects with the word “report” in their name.

The “NotLike” Operator in PowerShell
Sometimes, you’ll want to retrieve elements that don’t match a pattern. The NotLike operator works similarly to the -NE operator, but the right-hand side operator may contain wildcards. Use the -notlike operator for this.
$strings -notlike "pattern"
$names = @("Alice", "Alicia", "Alisha")
$names | Where-Object { $_ -notlike "Alic*" } # Returns AlishaNow “Alisha” is returned because it does not start with “Alic”. We can also filter other kinds of objects, like processes:
Get-Process | Where-Object Name -notlike "*Shell*"
This gets all processes except those containing “Shell” in the name.

Other posts
View all service principals API permissions
What’s the point of PowerShell?
Powershell is a tool that can be used to accomplish/automate anything you can do in a Windows GUI, essentially. Actually knowing how to write your own scripts or modify scripts you found online is an invaluable skill to know. A vast majority (probably over 95%) of companies have Windows operating systems in their environment for desktops, servers, or cloud technology; which means they are often desperate for somebody with a PowerShell skillset. It’s also worth mentioning that some configuration items in Windows are NOT available in the GUI, and can only be accomplished using PowerShell or other scripting languages like C#.
PowerShell If Like – Conditional Statement
PowerShell if like is a conditional statement that allows you to perform an action based on whether a string matches a specific pattern or not. This statement is commonly used in PowerShell scripts and commands to perform an action based on the contents of a string.
if ($string -like "pattern") { # Do something
}In this syntax, $string is the string that you want to compare and "pattern" is the pattern that you want to match against the string. The code inside the curly braces will be executed if the string matches the specified pattern.
$string = "Apple"
if ($string -like "A*") { Write-Host "The string starts with the letter A"
}This command will output the message “The string starts with the letter A”, as the string “Apple” starts with the letter “A”.
-like vs. -match, -like vs. contains
-like vs. -match:
While -like uses wildcards for pattern matching, -match operator uses regex pattern (regular expressions). They are powerful but also more complex.
"PowerShell" -match "^Power" # True, using regex to match the start of a string
-like vs. contains:
The contains operator checks if an array contains a specific value, whereas -like checks if a string matches a pattern.
$array = @("apple", "banana", "cherry")
$array -contains "banana" # TrueStep 1 — Fetching the data we need
Alright now to finally begin writing our script. There is a cmdlet in PowerShell called Get-Childitem (equivalent of ls or dir) that lists files in our directory, and perhaps we can then get the contents of those files to look for the data we need? Let’s try it out.
Looks promising thus far! Let’s use the dummy terminal at the bottom and press Enter to execute the command to see what the output looks like:
Alternatively, we can highlight our code and click the green ‘Run Selection’ button at the top of ISE to get the same output:
Okay, great, now we have an idea of what our root directory looks like. Get-Childitem has a -recurse ‘switch’ (parameter) which can be added to our command to recursively dig down into sub-directories of the path we give. By the way, Get-Help Get-childitem -Examples is very useful here. Note the difference in output. We will use this so we can actually grab all of the necessary files we want to get content from.
Now that we have found a method to drill down into sub-directories, let’s consider how we’re going to now take a look at the content from those files. There are some useful cmdlets we can consider for this task, such as Get-Content which will get all the content of a file, or Select-String which will search through a file for a certain string/pattern. The second option sounds better as the pattern matching portion is built into the cmdlet, but lets try some different methods. Here are some of the ways we can accomplish what we’re looking for:
Method #1 (preferred solution)
We use the Get-Childitem cmdlet and specify the path we’re looking for, as well as recursive parameter to enumerate sub-directories as well. We then pipe this output to the Select-String cmdlet and specify the patterns we are looking for. The output shows us the path of the file, the line number, and the output we are looking for. The concept of ‘piping’ output is essentially taking a data buffer in-memory, and feeding it into another command as input.
Method #2 (meh)
We save all of the output from Get-Childitem into a variable. We then create a ‘foreach’ loop, take each of those individual files one-by-one and pipe them into a select-string cmdlet. **note the variable names you can make up yourself.
Method #3 (worst)
We save all output from Get-Childitem into a variable. We then create a foreach loop and pipe each of those individual files to Get-Content and furthermore pipe that output to Select-String. We are going overboard here, and our output is not as pretty (no name of file, no line number, etc.) We could of course save those to other variables, create a custom object, and output that information. But that is more useless code, since select-string already does all of this for us without the get-content, and much more efficiently!
Matching Multiple Values with -Like in PowerShell
Here is an example of using the PowerShell -like operator to match multiple values in a string:
$string = "cat, dog, turtle" $string -like "*cat*" $string -like "*dog*" $string -like "*turtle*"
This searches the string for the presence of “cat”, “dog”, and “turtle” using -like with wildcards.
To match the entire string, we can chain -like with -and:
$string -like "*cat*" -and $string -like "*dog*" -and $string -like "*turtle*"
Now, it will only return True if all three animals are found. Here is another example of using -Or operator:
$usernames = @("john", "alice!", "bob#", "charlie$", "dave")
$usernames | Where-Object { $_ -like "*!*" -or $_ -like "*#*" -or $_ -like "*$*" }This gets all the values with special characters !#$: alice!, bob#, charlie$
Using -like with the Switch Statement
We can also use -like with a switch statement to check multiple patterns. The switch statement also supports -like for pattern matching:
$name = "John"
switch ($name) { {$_ -like "Jo*"} {"Name starts with Jo"} {$_ -like "*hn"} {"Name ends with hn"}
}This prints “Name starts with Jo” since $name matches the first pattern. Here is another way of using wildcard expression in the Switch statement:
switch -Wildcard ($string) { "*cat*" {Write-Host "Found cat"} "*dog*" {Write-Host "Found dog"} "*turtle*" {Write-Host "Found turtle"}
}This switches over $string and prints a message if any of the -like wildcard patterns match.
Escaping Wildcard Characters with Like Operator
To match literal characters like *, ? Instead of wildcards, escape them with regular expressions:
- *: Represents zero or more characters.
- ?: Represents a single character.
$queries = @("What's PowerShell?", "How to code?", "Learn PowerShell")
$queries | Where-Object { $_ -like "*[?]" }
# Returns "What's PowerShell?" and "How to code?"How to know which cmdlet to use? What about syntax?
As you can see, it shows syntax as well as usage examples, and some fake output, so you know what to expect.
The command: Get-command * will list all of the available commands on your system.
Conclusion and Next Steps
What is the -like operator in PowerShell?
The -like operator in PowerShell is used to perform wildcard pattern matching on strings. It allows you to check if a string matches a specified wildcard pattern. For example: $filename -like '*.txt'
How do I use the -Like operator to match a specific pattern?
To use the -Like operator for pattern matching, you can specify the pattern using wildcard characters. For example: "apple" -Like "a*" will return $true because the string “apple” starts with the letter “a”.
What are the wildcard characters used with -like?
Can I use multiple wildcard patterns with -like?
Yes, you can use multiple wildcard patterns by separating them with the -or operator. For example: $FileName = "C:\Temp\file.txt"
$FileName -like '.txt' -or $FileName -like '.docx'
How does -like differ from -match?
Can I negate the -like operator?
Yes, you can negate the -notlike operator. This checks if the string does not match the specified wildcard pattern: $FileName -notlike '*.txt'
Is -like case-sensitive?
By default, -like is not case-sensitive. However, you can make it case-sensitive by using the -clike (case-like) operator.
Can I use the -Like operator with arrays or collections?
Yes, you can use the -Like operator with arrays or collections. It will return all the elements that match the specified pattern. For example: "apple", "banana", "cherry" -Like "*a*" will return “apple” and “banana”.
How can I use the -like operator to filter an array or collection?
Recap and Key Takeaways
At its core, the -like operator in PowerShell facilitates wildcard string comparison. It checks if a string conforms to a specified pattern, enabling both exact and fuzzy matches. The main points about PowerShell’s -like operator covered in this post include:
-likecompares strings using wildcard pattern matching- Use
*and?Wildcards to match text patterns - Filter collections like arrays with
-likeand-notlike - Works on hashtables, arrays, processes, and more
- Implement case-insensitive matching with
-clike - Escape special chars to match them literally
- Combine with
-and,-or,-notfor complex logic
In summary, the -like operator provides powerful string pattern matching capabilities in PowerShell, similar to SQL queries. Using -like and -notlike makes it easy to search and filter text strings in your PowerShell scripts. PowerShell also supports a wide range of comparison operators (Eq, Ne, Lt, Gt, Ge, Le, etc.). Here is my other article: How to use Comparison Operators in PowerShell?



