How to use method / functions

This topic contains 3 replies, has 3 voices, and was last updated by  Curtis Smith 3 weeks ago.

  • Author
    Posts
  • #84785

    Sankhadip Roy
    Participant

    Hi PowerGuyz,

    I am still swimming in the basic of PowerShell, watch multiple videos, following books and forums. Can use multiple cmdlets, pipe them, can operate them etc. Yet if my question looks very silly please don't mind.

    In PowerShell, every object has its own type of members. I am confident about the property members only, but in real-world cases, I need to know the methods, functions, script property etc. My question is how to know what a method/function/script property does? How to use them? For example, I checked that Get-date cmdlet has many method and peoples are using them, from their usage I learn those methods can be used that way. Even now I can also use those methods. But the question is what about others? From where I get help/guide, after which I can also manipulate them.

    Regards,
    Sankhadip Roy.

  • #84796

    Sam Boutros
    Participant

    Use Get-Member to identify 'TypeName'. In this case it's 'System.DateTime'
    Google/bing 'System.DateTime methods' to find the relevant MSDN doc(s). In this case https://msdn.microsoft.com/en-us/library/system.datetime_methods(v=vs.110).aspx

    Get-Date | Get-Member
    
    
       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.CompareTo(Sy...
    Equals               Method         bool Equals(System.Object value), bool Equals(datetime value), bool IEquatable[datetime].Equals...
    GetDateTimeFormats   Method         string[] GetDateTimeFormats(), string[] GetDateTimeFormats(System.IFormatProvider provider), st...
    GetHashCode          Method         int GetHashCode()                                                                                 
    GetObjectData        Method         void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Ru...
    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.IFormatProvider provi...
    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()                                                                        
    DisplayHint          NoteProperty   DisplayHintType DisplayHint=DateTime                                                              
    Date                 Property       datetime Date {get;}                                                                              
    Day                  Property       int Day {get;}                                                                                    
    DayOfWeek            Property       System.DayOfWeek DayOfWeek {get;}                                                                 
    DayOfYear            Property       int DayOfYear {get;}                                                                              
    Hour                 Property       int Hour {get;}                                                                                   
    Kind                 Property       System.DateTimeKind Kind {get;}                                                                   
    Millisecond          Property       int Millisecond {get;}                                                                            
    Minute               Property       int Minute {get;}                                                                                 
    Month                Property       int Month {get;}                                                                                  
    Second               Property       int Second {get;}                                                                                 
    Ticks                Property       long Ticks {get;}                                                                                 
    TimeOfDay            Property       timespan TimeOfDay {get;}                                                                         
    Year                 Property       int Year {get;}                                                                                   
    DateTime             ScriptProperty System.Object DateTime {get=if ((& { Set-StrictMode -Version 1; $this.DisplayHint }) -ieq  "Dat...
    
    
    • #84880

      Sankhadip Roy
      Participant

      Hi Sam,

      Thanks for the guidance. Your answer clears my doubt 50%, the next 50% is how to use them? From morning I am going through multiple type name and looking their details in MSDN. But still, I can't figure it out, how to use them, here is an example, I run the following command and redirect the output to a text file.
      dir > append.txt
      Now as per System.IO.FileInfo methods, there is one named AppendText() whose description says "Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo." I can understand that this method can append more data to a file. So next I tried this command to append some data to the previous file.
      (dir -Filter *.png).AppendText(append.txt)
      and as usual, I got following error.

      At line:1 char:32
      + (dir -Filter *.png).AppendText(append.txt)
      + ~
      Missing ')' in method call.
      At line:1 char:32
      + (dir -Filter *.png).AppendText(append.txt)
      + ~~~~~~~~~~
      Unexpected token 'append.txt' in expression or statement.
      At line:1 char:42
      + (dir -Filter *.png).AppendText(append.txt)
      + ~
      Unexpected token ')' in expression or statement.
      + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
      + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

      This is the issue, I need some guidance about its usage. Right now I am guessing and trying based on MSDN description. Not for this method, for other methods too. I am not from programming track, might be for that I can't understand. But if you can help to guide further or share me some resources from where I can learn, that will be really a lot for me.

      Regards,
      Roy.

  • #84886

    Curtis Smith
    Participant

    In order to use the .Net methods, you need to use them as defined by their syntax.

    As showing in the get-member of AppendText, this method accepts no parameters

    AppendText                Method         System.IO.StreamWriter AppendText()

    This is confirmed by Microsoft's documentation (https://msdn.microsoft.com/en-us/library/system.io.fileinfo.appendtext(v=vs.110).aspx). It just creates a StreamWriter.

    You can then used the methods of that StreamWriter, such as write or writeline, to append the text you want to the file.

    PS C:\> (dir desktop.lnk).AppendText() | Get-Member
    
    
       TypeName: System.IO.StreamWriter
    
    Name                      MemberType Definition                                                                                              
    ----                      ---------- ----------                                                                                              
    Close                     Method     void Close()                                                                                            
    CreateObjRef              Method     System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)                                         
    Dispose                   Method     void Dispose(), void IDisposable.Dispose()                                                              
    Equals                    Method     bool Equals(System.Object obj)                                                                          
    Flush                     Method     void Flush()                                                                                            
    FlushAsync                Method     System.Threading.Tasks.Task FlushAsync()                                                                
    GetHashCode               Method     int GetHashCode()                                                                                       
    GetLifetimeService        Method     System.Object GetLifetimeService()                                                                      
    GetType                   Method     type GetType()                                                                                          
    InitializeLifetimeService Method     System.Object InitializeLifetimeService()                                                               
    ToString                  Method     string ToString()                                                                                       
    Write                     Method     void Write(char[] buffer, int index, int count), void Write(char value), void Write(char[] buffer), v...
    WriteAsync                Method     System.Threading.Tasks.Task WriteAsync(char value), System.Threading.Tasks.Task WriteAsync(string val...
    WriteLine                 Method     void WriteLine(), void WriteLine(char value), void WriteLine(char[] buffer), void WriteLine(char[] bu...
    WriteLineAsync            Method     System.Threading.Tasks.Task WriteLineAsync(), System.Threading.Tasks.Task WriteLineAsync(char value),...
    AutoFlush                 Property   bool AutoFlush {get;set;}                                                                               
    BaseStream                Property   System.IO.Stream BaseStream {get;}                                                                      
    Encoding                  Property   System.Text.Encoding Encoding {get;}                                                                    
    FormatProvider            Property   System.IFormatProvider FormatProvider {get;}                                                            
    NewLine                   Property   string NewLine {get;set;}                                                                               
    

    It's also worth noting that the appendtext method is available on a single System.IO.FileInfo object. In your example you used dir -Filter *.png, which could result in a collection of System.IO.FileInfo objects. The appendtext method would not be available on that collection. You would need to loop through the collection and do the appendtext on each object in the collection if desired.

You must be logged in to reply to this topic.