Reordering columns in a DataTable

If you need the columns in a DataTable in a specific order, you just create them in the order you need, right? But what if you are dealing with a DataTable full of data?

I wrote about ConvertTo-DataTable before, a function that let’s you convert a regular PowerShell object into a DataTable. This is a great time saver for creating and populating a table with data.

Now I’m going to show you how you can easily change the column order in a DataTable.

Consider the following:
columnordering01
Here we use Get-Service to get an object containing all the services and convert this object to a DataTable. We then get list all the column names.

But what if we require the Status column to come right after the Name? Let’s do this:
columnordering02
We start by getting the DataColumn we need, and use the SetOrdinal method to give it a new index value. As you see the Status column is now placed after the Name, just like we wanted it to. Easy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s