Monday, 15 June 2015

Manipulating object tables in Powershell.

Last week I posted about creating object tables in Powershell. This was mainly for the purpose of being able to use Export-CSV to send the data out to a CSV file. This time I am going to have a brief look at some of the other things you can do with an object table, which is a convenient way of having a simple database that you can store data in and process it through your script.

Since the object table is basically an array of objects, it can be manipulated using the basic array operators. Such as:
  • Append an instance: += which most people will recognise as the standard increment operator borrowed from C/C++.
  • Retrieve an instance by index: e.g. $S[0] returns the first instance
  • Retrieve a range of instances by index e.g. $S[4..9], $S[1,2+4..9]
  • Retrieve the last instance: $S[-1] which is great as you don't need to know how big the array is to use this.
Obviously we don't need to use typical database methods like First, Last, Next and Previous which are often provided to step through a table's records. Instead just index the array.