Parameter types when writing cmdlets in C#

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of  Anonymous 1 year, 11 months ago.

  • Author
    Posts
  • #26684
    Profile photo of
    Anonymous

    What is the suggested best practice for writing a cmdlet that receives input by the pipeline with regards to the type of the parameter that receives values? For example, if the cmdlet I want to write needs a path, you expect the user to adjust the syntax used by GCI to only return System.IO.FileInfo, however if they dont and I get System.IO.DirectoryInfo objects, from the Powershell users perspective, should this raise and be left to the configured erroraction?

    Thanks!

  • #26692
    Profile photo of Richard Diphoorn
    Richard Diphoorn
    Participant

    I'm not a programmer myself, but Tobias Weltner wrote about writing your own Cmdlets in his PowerShell book. Maybe it helps you answering your question: Your Own Cmdlets and Extensions

    I can also recommend Doug Finke's book for you: PowerShell for Developers

  • #26726
    Profile photo of
    Anonymous

    Hi Richard,
    I managed to catch a session on Pluralsight by Jimmy Skowronski titled 'Extending Powershell' where I noticed his pattern and learnt the simple nature of this task.

    namespace PowerShellCourse
    {
      [Cmdlet(VerbsDiagnostic.Test, "Parameters")]
      public class TestParametersCommand : PSCmdlet
      {
        [Parameter(ValueFromPipelineByPropertyName = true)]
        public string FullName { get; set; }
    
        [Parameter(Position = 1, ValueFromPipeline = true)]
        public FileInfo File { get; set; }
    
        [Parameter(ValueFromPipeline = true)]
        public DirectoryInfo Folder { get; set; }
    
        protected override void ProcessRecord()
        {
          WriteObject(new { Folder = Folder, File = File, FullPath = FullName });
        }
      }
    }
    

    So pretty much all options and the basic string parameter can be made available.
    Thanks!

  • #26729
    Profile photo of Richard Diphoorn
    Richard Diphoorn
    Participant

    Great you found out! Out of curiosity, what type of Cmdlet are you going to write? Or is this to train yourself into doing it?

  • #26887
    Profile photo of
    Anonymous

    Sorry Richard, I am not getting subscribed notifications?

    Anyway, the cmdlet receives output from Get-ChildItem where filtered content are XML files. For a specified type (several are supported) it deserializes the XML files and searches based on a quantity of type specific criteria. For example, if you choose type A and search by first and last name matching some string, it returns all the matching XML files to the pipeline. If you switch types, the cmdlet alters the actual criteria used by that deserialized type. So all you need to know is the type and your criteria abstracted to a common parameter, like "FirstName".

You must be logged in to reply to this topic.