Skip to main content

Describing Object Methods

Yesterday, we took a look at how the properties of an object allows us to easily consume information.  The next object member we are going to look at are methods. Methods are awesome.  They essentially are free code that you can utilize so you do not need to write it yourself.  A method is usually an action that an object can on itself.  Take a look at the methods that are provided from the System.Datetime object that is produced by Get-Member.

PS C:\> Get-Date | Get-Member -MemberType Methods


   TypeName: System.DateTime

Name                 MemberType Definition                                                                            
----                 ---------- ----------                                                                            
Add                  Method     datetime Add(timespan value)                                                          
AddDays              Method     datetime AddDays(double value)                                                        
AddHours             Method     datetime AddHours(double value)                                                       
AddMilliseconds      Method     datetime AddMilliseconds(double value)                                                
AddMinutes           Method     datetime AddMinutes(double value)                                                     
AddMonths            Method     datetime AddMonths(int months)                                                        
AddSeconds           Method     datetime AddSeconds(double value)                                                     
AddTicks             Method     datetime AddTicks(long value)                                                          
AddYears             Method     datetime AddYears(int value)                                                          
CompareTo            Method     int CompareTo(System.Object value), int CompareTo(datetime value), int IComparable.C...
Equals               Method     bool Equals(System.Object value), bool Equals(datetime value), bool IEquatable[datet...
GetDateTimeFormats   Method     string[] GetDateTimeFormats(), string[] GetDateTimeFormats(System.IFormatProvider pr...
GetHashCode          Method     int GetHashCode()                                                                     
GetObjectData        Method     void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info...
GetType              Method     type GetType()                                                                        
GetTypeCode          Method     System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()             
IsDaylightSavingTime Method     bool IsDaylightSavingTime()                                                           
Subtract             Method     timespan Subtract(datetime value), datetime Subtract(timespan value)                  
ToBinary             Method     long ToBinary()                                                                       
ToBoolean            Method     bool IConvertible.ToBoolean(System.IFormatProvider provider)                          
ToByte               Method     byte IConvertible.ToByte(System.IFormatProvider provider)                             
ToChar               Method     char IConvertible.ToChar(System.IFormatProvider provider)                              
ToDateTime           Method     datetime IConvertible.ToDateTime(System.IFormatProvider provider)                     
ToDecimal            Method     decimal IConvertible.ToDecimal(System.IFormatProvider provider)                        
ToDouble             Method     double IConvertible.ToDouble(System.IFormatProvider provider)                         
ToFileTime           Method     long ToFileTime()                                                                     
ToFileTimeUtc        Method     long ToFileTimeUtc()                                                                  
ToInt16              Method     int16 IConvertible.ToInt16(System.IFormatProvider provider)                           
ToInt32              Method     int IConvertible.ToInt32(System.IFormatProvider provider)                             
ToInt64              Method     long IConvertible.ToInt64(System.IFormatProvider provider)                            
ToLocalTime          Method     datetime ToLocalTime()                                                                
ToLongDateString     Method     string ToLongDateString()                                                             
ToLongTimeString     Method     string ToLongTimeString()                                                             
ToOADate             Method     double ToOADate()                                                                     
ToSByte              Method     sbyte IConvertible.ToSByte(System.IFormatProvider provider)                           
ToShortDateString    Method     string ToShortDateString()                                                            
ToShortTimeString    Method     string ToShortTimeString()                                                            
ToSingle             Method     float IConvertible.ToSingle(System.IFormatProvider provider)                          
ToString             Method     string ToString(), string ToString(string format), string ToString(System.IFormatPro...
ToType               Method     System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider)
ToUInt16             Method     uint16 IConvertible.ToUInt16(System.IFormatProvider provider)                         
ToUInt32             Method     uint32 IConvertible.ToUInt32(System.IFormatProvider provider)                         
ToUInt64             Method     uint64 IConvertible.ToUInt64(System.IFormatProvider provider)                         
ToUniversalTime      Method     datetime ToUniversalTime()        

What does all of this mean?  Well, let’s use this as an example.  It is December 31, 1999 at 23:59:59. Now, add 2 seconds to this DateTime object.  You need to provide the intelligence to your code to know:

  •       There are 60 seconds per minute
  •       There are 60 minutes per hour
  •       There are 24 hours in a day
  •       There are 31 days in December
  •       There are 12 months in a year
  •       December is the last month of the year.
  •       January is the first month of the year.


That sounds a bit daunting. Why do it when the System.DateTime object already has done this for you. Let’s first create the Datetime object to represent our situation.

PS C:\> Get-Date -Year 1999 -Month 12 -Day 31 -Hour 23 -Minute 59 -Second 59

Friday, December 31, 1999 11:59:59 PM

From the member information above, take note of the method called AddSeconds().  It accepts one argument.  That is the number of seconds that you want to add to the DateTime object.  Here are a few ways how to use it to add 2 seconds to our DateTime object and roll in the year 2000.

# Dot notation
(Get-Date -Year 1999 -Month 12 -Day 31 -Hour 23 -Minute 59 -Second 59).AddSeconds(2)

# Object enumeration with the basic syntax of ForEach-Object
Get-Date -Year 1999 -Month 12 -Day 31 -Hour 23 -Minute 59 -Second 59 |
    ForEach-Object -MemberName AddSeconds -ArgumentList 2

# Object enumeration with the advanced syntax of ForEach-Object
Get-Date -Year 1999 -Month 12 -Day 31 -Hour 23 -Minute 59 -Second 59 |
    ForEach-Object -Process {$_.AddSeconds(2)}

# Using a variable with dot notation
$Date = Get-Date -Year 1999 -Month 12 -Day 31 -Hour 23 -Minute 59 -Second 59
$Date.AddSeconds(2)

# Using a .NET constructor for System.DateTime and dot notation
([Datetime]$Date = "12/31/1999 23:59:59").AddSeconds(2)

Any of these solutions will give you the result.
Saturday, January 1, 2000 12:00:01 AM


Much easier than trying to code this object yourself. As with properties, you can find a variety of different methods in the online documentation at MSDN.

Comments

Popular posts from this blog

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of. This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago. In the Group Policy module for PowerShell V3, th

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple. # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   # Remove the duplicate values. $Set1 | Select-Object -Unique 1 2 3 4 5 6 7 What if you want only the duplicate values and nothing else? # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   #Create a second collection with duplicate values removed. $Set2 = $Set1 | Select-Object -Unique   # Return only the duplicate values. ( Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1 ) . InputObject | Select-Object – Unique 1 2 This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are diffe

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.