locked
Powershell custom object -ask for help to make my script more simple RRS feed

  • Question

  • Hi Guys

    I'm new to powershell and I wrote a script to create custom object as below.

    ====================================================

    $users = 'jacky','parker','andy'
    $sids = '1','2','3'
    $mobile = '123','456','789'


    $objs = @()


    for($i=0;$i -lt $users.Length;$i++)
    {
        $name = $users[$i]
        $sid = $sids[$i]
        $phone = $mobile[$i]
       
        $ad_user = New-Object -TypeName PSOBJECT -Property (
                                              @{'DispalyName'=$name;
                                                'SID'=$sid;
                                                'MobilePhone'=$phone})   
        $objs += $ad_user

    }

    $objs

    =========================================

    the output was below

    DispalyName SID MobilePhone
    ----------- --- -----------
    jacky       1   123       
    parker      2   456       
    andy        3   789 

    My question was can someone help to make my script a little simple since I thought it should have some way to make the script shorter.

    Thanks

    Jacky

    Monday, August 15, 2016 1:25 PM

Answers

  • You can use the [pscustomobject] accelerator as long as you're running at least v3.

    $users = 'jacky','parker','andy'
    $sids = '1','2','3'
    $mobile = '123','456','789'
    
    $obj = for ($i = 0 ; $i -lt $users.Length ; $i++) {
    
        [pscustomobject]@{
            DisplayName = $users[$i]
            SID = $sids[$i]
            MobilePhone = $mobile[$i]
        }
    
    }
    
    $obj


    • Proposed as answer by FWN Monday, August 15, 2016 2:09 PM
    • Marked as answer by Richard MuellerMVP Saturday, August 27, 2016 9:30 PM
    Monday, August 15, 2016 1:50 PM

All replies

  • You can use the [pscustomobject] accelerator as long as you're running at least v3.

    $users = 'jacky','parker','andy'
    $sids = '1','2','3'
    $mobile = '123','456','789'
    
    $obj = for ($i = 0 ; $i -lt $users.Length ; $i++) {
    
        [pscustomobject]@{
            DisplayName = $users[$i]
            SID = $sids[$i]
            MobilePhone = $mobile[$i]
        }
    
    }
    
    $obj


    • Proposed as answer by FWN Monday, August 15, 2016 2:09 PM
    • Marked as answer by Richard MuellerMVP Saturday, August 27, 2016 9:30 PM
    Monday, August 15, 2016 1:50 PM
  • Thanks Man
    Tuesday, August 16, 2016 7:58 AM
  • Cheers, you're welcome.

    Tuesday, August 16, 2016 12:10 PM