PoshBytes: What the Method

PoshBytes: What the Method

What is a method in PowerShell and why should you care. In this episode of PoshBytes, we break down what methods are, how to call them, and how to discover them using real examples.

This post is a companion for the video embedded below. Scroll down to see the code from the video.

https://youtube.com/shorts/ab8jxoGQ-4M

Example of something

Create a simple string object and call a method on it

$text = "poshbytes rules"
$text.ToUpper()

Replace part of the string

$text.Replace("rules","rocks")

Discover properties and methods

$text | Get-Member

Show only methods

$text | Get-Member -MemberType Method

Work with a DateTime object

$now = Get-Date
$now | 
  Get-Member -MemberType Method -Name Add* |
  Format-Table Name, Definition
$now.AddDays(7)

Using Methods in Script Logic

Use a method inside conditional logic

if ($now.IsDaylightSavingTime()) {
    "Move to Arizona"
}
else {
    "Standard time rules the land."
}

Stringing string methods to create a string of string

$text = "poshbytes rules"
$text.Substring(0,1).ToUpper().Insert(1,$text.Substring(1,$text.IndexOf("b")-1).Insert($text.IndexOf("b")-1,$text.Substring($text.IndexOf("bytes"),1).ToUpper().Insert(1,$text.Substring($text.IndexOf("bytes")+1).Replace("rules", "Rocks"))))

Wrap Up

• Methods are actions objects can perform
• Use dot notation to call them
• Parentheses mean you are invoking a method
• Use Get-Member to discover available methods
• Filter with -MemberType Method to focus on actions

Leave a Reply

Your email address will not be published. Required fields are marked *