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

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.

How to run GPResult on a remote client with PowerShell

In the past, to run the GPResult command, you would need to either physically visit this client, have the user do it, or use and RDP connection.  In all cases, this will disrupt the user.  First, you need PowerShell remoting enabled on the target machine.  You can do this via Group Policy . Open PowerShell and type this command. Invoke-Command –ScriptBlock {GPResult /r} –ComputerName <ComputerName> Replace <ComputerName> with the name of the target.  Remember, the target needs to be online and accessible to you.

Error icon when creating a GPO Preference drive map

You may not have an error at all.  Take a look at the drive mapping below. The red triangle is what threw us off.  It is not an error.  It is simply a color representation of the Replace option of the Action field in the properties of the drive mappings. Create action This give you a green triangle. The Create action creates a new mapped drive for users. Replace Action The Replace action gives you a red triangle.  This action will delete and recreate mapped drives for users. The net result of the Replace action is to overwrite all existing settings associated with the mapped drive. If the drive mapping does not exist, then the Replace action creates a new drive mapping. Update Action The Update action will have a yellow triangle. Update will modify settings of an existing mapped drive for users. This action differs from Replace in that it only updates settings defined within the preference item. All other settings remain as configured on the mapped drive. If the