How do I create a custom type in PowerShell for my scripts to use?

后端 未结 8 1299
遥遥无期
遥遥无期 2020-12-22 18:29

I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let\'s pretend I had a need for an object that had the following struc

8条回答
  •  庸人自扰
    2020-12-22 19:18

    Creating custom types can be done in PowerShell.
    Kirk Munro actually has two great posts that detail the process thoroughly.

    • Naming Custom Objects
    • Defining Default Properties for Custom Objects

    The book Windows PowerShell In Action by Manning also has a code sample for creating a domain specific language to create custom types. The book is excellent all around, so I really recommend it.

    If you are just looking for a quick way to do the above, you could create a function to create the custom object like

    function New-Person()
    {
      param ($FirstName, $LastName, $Phone)
    
      $person = new-object PSObject
    
      $person | add-member -type NoteProperty -Name First -Value $FirstName
      $person | add-member -type NoteProperty -Name Last -Value $LastName
      $person | add-member -type NoteProperty -Name Phone -Value $Phone
    
      return $person
    }
    

提交回复
热议问题