Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Sunday, December 4, 2016

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

# 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.

No comments: