PowerShell is a powerful and versatile scripting language that is very useful for automating processes. I often look for how others have solved a particular problem. I want to share some, not all — sorry– :), handy tricks that I have collected over time with you here. They are not complete scripts but rather a collection of useful snippets that you can use in your own scripts. Most examples come from the PowerShell community, and I have gathered them here for you. I hope you find them helpful.
Index
- Adding Leading Zeros to Numbers
- Generating Server Names with Leading Zeros
- Retrieving the Scriptblock Content of a Loaded Function
- Calculating the Duration of Your PowerShell Session
- Calculating the Duration of Other Processes
- Generating a Formatted Report of All Commands of a Module with a Synopsis
Adding Leading Zeros to Numbers
Take, for example, the situation where you have a list of numbers that need a leading ‘0’. You can do this in several ways.
The first way is with the ‘-f’ operator. This operator can be used to format a string. In this case, I want the number to always have 3 digits, so I use ‘D3’ as the formatting. The result is that the number always has 3 digits, with leading zeros if necessary.
The second way is with the ‘ToString’ method. This method can be used to format a number into a string. In this case, I want the number to always have 4 digits, so I use ‘D4’ as the formatting. The result is that the number always has 4 digits, with leading zeros if necessary.
$number = 2
# Method 1: Using the format operator
$method01 = '{0:D3}' -f $number
# Result: 002
# Method 2: Using the ToString method
$method02 = $number.ToString('D4')
# Result: 0002
Generating Server Names with Leading Zeros
You can then, for example, expand this to a list of servers.
1..15 | foreach-object {
$servername = "Server$($_.ToString('D2'))"
$servername
}
# Result:
Server01
Server02
...
Server14
Server15
Retrieving the Scriptblock Content of a Loaded Function
Another example of something that can be very useful is retrieving the scriptblock content of a loaded function. You can do this by replacing the name of the function in the ‘get-item’ cmdlet. This can be handy if you want to know exactly what is in the function without having to open the function itself. You can then store this in a variable and use it in your script.
(get-item Function:\Get-Testoutput).scriptblock
If you only want to read the content of your function, you can also use the ‘get-content’ cmdlet. The code below displays the content of the ‘Testoutput’ function.
Get-Content function:\Get-Testoutput
Calculating the Duration of Your PowerShell Session
You can calculate how long your PowerShell session has been running with this command:
(Get-Date) - (get-process -id $pid).starttime
Days : 0
Hours : 0
Minutes : 27
Seconds : 42
Milliseconds : 216
Ticks : 16622163913
TotalDays : 0,0192386156400463
TotalHours : 0,461726775361111
TotalMinutes : 27,7036065216667
TotalSeconds : 1662,2163913
TotalMilliseconds : 1662216,3913
Calculating the Duration of Other Processes
You can, of course, also read the runtime of all processes. Not all processes return a runtime. You can solve this by using the ‘try’ and ‘catch’ blocks. Below is an example of how you can do this. This provides an overview of all processes with their name, start time, and runtime.
# Get all running processes
$processes = Get-Process
# Calculate the duration for each process
$processes | ForEach-Object {
$duration = Try {
(Get-Date) - $_.StartTime
} catch {}
[PSCustomObject]@{
ProcessName = $_.Name
StartTime = $_.StartTime
Duration = $duration
}
} | Format-Table -AutoSize
Generating a Formatted Report of All Commands of a module with a Synopsis
When working with PowerShell modules, it’s often helpful to explore the functions they provide and understand their purpose.
# Replace 'ModuleName' with the name of the module you want to query
$moduleName = 'ModuleName'
# Get all functions from the specified module
Get-Command -Module $moduleName -CommandType Function |
Sort-Object Name |
Format-Table -Property Name, @{Name = "Synopsis"; Expression = {(Get-Help $_.Name).Synopsis.Trim()}}
# example usage with oh-my-posh-core module
Name Synopsis
---- --------
Enable-PoshLineError Enable-PoshLineError
Enable-PoshTooltips Enable-PoshTooltips
Enable-PoshTransientPrompt Enable-PoshTransientPrompt
prompt prompt
Set-PoshContext Set-PoshContext [[-originalStatus] <bool>]
This snippit is a handy tool for PowerShell users who want to explore and document modules efficiently. Try it out with your favorite module and see how much time it saves!
Leave a Reply