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

后端 未结 8 1297
遥遥无期
遥遥无期 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:16

    There is the concept of PSObject and Add-Member that you could use.

    $contact = New-Object PSObject
    
    $contact | Add-Member -memberType NoteProperty -name "First" -value "John"
    $contact | Add-Member -memberType NoteProperty -name "Last" -value "Doe"
    $contact | Add-Member -memberType NoteProperty -name "Phone" -value "123-4567"
    

    This outputs like:

    [8] » $contact
    
    First                                       Last                                       Phone
    -----                                       ----                                       -----
    John                                        Doe                                        123-4567
    

    The other alternative (that I'm aware of) is to define a type in C#/VB.NET and load that assembly into PowerShell for use directly.

    This behavior is definitely encouraged because it allows other scripts or sections of your script work with an actual object.

提交回复
热议问题