Costa Zachariou Costa Zachariou - 3 months ago 9
PowerShell Question

Sorting using the sort object in PowerShell part 3

Changed my code a little from part 2 example below but taking part 2 example which works great thanks to a member in stackoverflow.

[string] $Source = 'e:\Temp\DataFromSkywardEdited.csv';
[string] $Destination = 'e:\Temp\DataFromSkywardRD.csv';
[object] $SortByColNames = 'LastName','FirstName';
[string] $ShowColsByNumber = "{0},{1},{2},{3},{4},{5},{6},{7},{8}";
[object] $ColumnValueFormat = '$_.EmployeeID.Trim()', '$_.FirstName.Trim()', '$_.LastName.Trim()', '$_.Location.Trim()', '$_.Department.Trim()', '$_.TelephoneNo.Trim()', '$_.Email.Trim()', '$_.EmpTypeCode.Trim()', '$_.EmployeeTypeDescription.Trim()';

Get-Content $Source |
ConvertFrom-Csv -Delimiter $Delimiter |
Sort-Object -Property $SortByColNames -Unique |
ForEach-Object {
# Each of the values in $ColumnValueFormat must be executed to get the property from the loop variable ($_).
$values = foreach ($value in $ColumnValueFormat) {
Invoke-Expression $value
}
# Then the values can be passed in as an argument for the format operator.
$ShowColsByNumber -f $values
} |
Add-Content $Destination


How would I make $ColumnValueFormat to be represented by numbers instead of a column name?

So instead of:

[object] $ColumnValueFormat = '$_.EmployeeID.Trim()', '$_.FirstName.Trim()', '$_.LastName.Trim()', '$_.Location.Trim()', '$_.Department.Trim()', '$_.TelephoneNo.Trim()', '$_.Email.Trim()', '$_.EmpTypeCode.Trim()', '$_.EmployeeTypeDescription.Trim()';


To something like:

[object] $ColumnValueFormat = '$_.[0].Trim()', '$_.[1].Trim()', '$_.[2].Trim()', '$_.[3].Trim()', '$_.[4].Trim()', '$_.[5].Trim()', '$_.[6].Trim()', '$_.[7].Trim()', '$_.[8].Trim()';

Answer

This really looks like you're doing it the hard way, but to directly answer your question, you would simply remove the period that preceeds the bracketed numbers. So...

[object] $ColumnValueFormat = '$_[0].Trim()', '$_[1].Trim()', '$_[2].Trim()', '$_[3].Trim()', '$_[4].Trim()', '$_[5].Trim()', '$_[6].Trim()', '$_.[7]Trim()', '$_[8].Trim()';