Skrevet av Emne: Powershell ARRAY tips and gotchas  (Lest 6288 ganger)

Utlogget Floyd-ATC

  • Livstidsdiktator
  • Administrator
  • Guru
  • *****
  • Innlegg: 542
  • Karma: +12/-0
    • MSN Messenger - floyd@atc.no
    • Vis profil
    • floyd.atc.no
    • E-post
Powershell ARRAY tips and gotchas
« på: 30. November 2011, 14:11 pm »
  • [applaud]0
  • [smite]0
  • Define an empty array:
    Kode: [Velg]
    $array = @();
    Define an array with data elements in it:
    Kode: [Velg]
    $array = [array]( "foo", "bar", "baz" );or
    Kode: [Velg]
    $array = @( "foo", "bar", "baz" );
    Note: Do NOT simply use $array = "foo", "bar", "baz" because if you later edit your code and specify only one element you won't get an array object anymore, possibly introducing weird problems.

    Access (read or write) an existing entry:
    Kode: [Velg]
    $element = $array[$index];and
    Kode: [Velg]
    $array[$index] = $element;Note: These will throw an exception if the array does not contain atleast $index+1 elements (the first entry is index 0)

    Add (push) an element to the end of an array:
    Kode: [Velg]
    $array += $element;
    Insert (unshift) an element at the beginning of an array:
    Kode: [Velg]
    $array = @($element) + $array;
    Remove (shift) first element from an array:
    Kode: [Velg]
    $element, $array = $array;
    Remove (pop) last element from an array:
    Kode: [Velg]
    [array]::Reverse($array);
    $element, $array = $array;
    [array]::Reverse($array);
    Note: After hours of scouring the web I have found no simpler, universally working way to pop the last element from an array. Many people recommend using slices and arithmetics, but those usually break in special cases. One can only hope (albeit, most likely in vain) that Microsoft have seen fit to implement the Reverse method in an efficient way.

    Get the number of entries in an array:
    Kode: [Velg]
    $count = @($array).Count;Note: Do NOT simply use $count = $array.Count because this will break if $array contains only one object and that object happens to come with its own Count method! (And yes, I spent some time finding that bug in my script...)

    List contents of an array:
    Kode: [Velg]
    $array
    Loop through an array:
    Kode: [Velg]
    foreach ($element in $array) {
      Write-Host $element;
    }

    Manually loop (C style) through an array:
    Kode: [Velg]
    for ($index=0; $index -lt $array.length ; $index++) {
      Write-Host $array[$index];
    }

    Manually loop (C style) in reverse:
    Kode: [Velg]
    for ($index=$array.length -1 ; $index -ge 0 ; $index--) {
      Write-Host $array[$index];
    }


    -Floyd.

    --
    Det finnes 10 typer mennesker;
    de som forstår binærtall, de som ikke gjør det, og de som forstår Grey code.