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'
}
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'
}
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
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"
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
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" }
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: $_" }
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"}
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
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
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
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"
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)
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.@{}
, 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.