Methods are another piece of what makes up an object. Methods are the actions we can take on an object, just like how a circle can grow or shrink, or a car can accelerate or brake.
When we use Get-Member
on a string-type object, we can see several methods available.
Object Method: Contains()
The Contains()
method of a string-type object returns a boolean whether or not a string contains the specified substring.
PS > $my_string = "Codecademy" PS > $my_string.Contains("Code") True
Object Method: Replace()
The Replace()
method of a string-type object replaces the specified substring on a string with another specified substring. It can also be used to delete a substring by replacing it with an empty string.
PS > $my_string = "Hello, World!" PS > $my_string.Replace("World", "Codecademy") Hello, Codecademy! PS > $my_string.Replace(", World", "") Hello!
Object Method: GetType()
The GetType()
method gets the type of an object, and therefore it is not exclusive to just string-type objects. It returns an object with several methods and properties, including the name of the type.
If we want to get the name of the type, we can access the Name
property. To print the type of an object, we used GetType().Name
.
PS > $num = 4 PS > $num.GetType().Name Int
We encourage you to run Get-Member -MemberType Method
on all types of objects and learn about their methods with various useful functionalities.
Instructions
In the PowerShell terminal, create a variable called $my_num
and assign it to the integer 5
.
Click the Check Work button to continue.
Show only methods of the variable named $my_num
.
Click the Check Work button to continue.
Use the CompareTo()
method of the $my_num
variable to compare it to another integer.
If the output is 1
, the specified integer is less than my_num
.
If the output is 0
, the specified integer is equal to my_num
.
If the output is -1
, the specified integer is more than my_num
.
Click the Check Work button to continue.
Use the ToString()
method of the $my_num
variable to convert the integer to a string. Save the string to a variable called $my_string
.
Click the Check Work button to continue.
Get the type of $my_string
variable using the Name
property of the GetType()
method.
Click the Check Work button to continue.