Powershell fixed width export

user2428207 picture user2428207 · Jan 15, 2015 · Viewed 8k times · Source

I am having a text file wich uses fixed width for separating columns.

I'm loading the file and create a new column which concatinates the values of the first two columns. The problem I have that when exporting the data I need to define a fixed column width of 13 for Column C.

Column A (3)   Column B(9)   Column C(13)
MMA            12345         12345_MMA
MMO            987222        987222_MMO

Basically for this example in the export I am missing 4 spaces for the first row and 3 for the second row.

Thisis my current code, which also includes a new row for MD5 creation.

    # Load input data
$PreSystem = [IO.File]::ReadAllText("C:\FILE.txt")

# Initiate md5-hashing
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding

# Split input data by lines
$all = $PreSystem.split("`n") 

# Loop over lines
for($i = 0; $i -lt $all.length-1; $i += 1) {
  # Access distinct lines
  $entry = "$($all[$i])"
  # Get the different parameters
  $market_code = $entry.substring(1,3)
  $soc = $entry.substring(4,9)
  # Hash the SOC element
  $hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($soc)))
  # Create desired format for each entry
  $output = $hash.Replace("-","")+$soc.Replace(" ","") + "_" + $market_code + $all[$i]
  # Write to file
  "$output" | Out-File -Filepath C:\"C:\FILE.txt" -Append -encoding ASCII

}

Thanks in advance

Answer

David Brabant picture David Brabant · Jan 15, 2015

You can create a custom table format using the tip explained here. Here is an example for Get-Process:

$a = @{Expression={$_.Name};Label="Process Name";width=25}, `
@{Expression={$_.ID};Label="Process ID";width=15}, `
@{Expression={$_.MainWindowTitle};Label="Window Title";width=40}

Get-Process | Format-Table $a

Basically, you build an expression through wich Format-Table will pipe each row. Instead of taking care of the formating yourself for each row, you build a hash and pipe it through Format-Table.