我必须将 txt 文件转换为固定宽度的文本文件。我正在学习 powershell,我创建了一个脚本来转换文件,但我对填充有问题(字段之间的空白)
我尝试:
# Define the input and output file paths
$inputFilePath = "C:\Users\Desktop\TEST_2.TXT"
$outputFilePath = "C:\Users\Desktop\TEST_3.TXT"
# Read the content of the input file, excluding the header line
$content = Get-Content $inputFilePath | Select-Object -Skip 1
# Initialize an empty array to store the formatted records
$formattedRecords = @()
# Loop through each line in the input file
foreach ($line in $content) {
# Split the line into fields based on whitespace (assuming fields are separated by spaces or tabs)
$fields = $line -split '\s+'
# Ensure that the line has at least 8 fields
if ($fields.Length -lt 8) {
Write-Host "Skipping record due to insufficient fields: $line"
continue
}
# Extract the fields
$recordType = $fields[0]
$employeeCode = $fields[1]
$facilityCode = $fields[2]
# Extract the official school name, considering a maximum length of 80 characters
$officialFacilitylName = $fields[3..10] -join ' '
$officialFacilitylName = $officialFacilitylName.Substring(0, [Math]::Min($officialFacilitylName.Length, 80)).PadRight(80)
# Filler length 15, start 92
$filler = " " * 15
$standardReportFlag = $fields[11]
$transmissionDate = $fields[12]
# Extract the degree period, considering a maximum length of 80 characters
$Period = $fields[13]
$Period = $degreePeriod.Substring(0, [Math]::Min($Period.Length, 80)).PadRight(80)
# Combine all the fields into a formatted record
$formattedRecord = "$recordType$employeeCode$facilityCode$officialFacilitylName$filler$standardReportFlag$transmissionDate$Period"
# Add the formatted record to the array
$formattedRecords += $formattedRecord
}
# Write the formatted records to the output file
$formattedRecords | Set-Content -Path $outputFilePath
# Output the number of records processed
Write-Host "Conversion complete. Processed $($formattedRecords.Count) records."
结果
B08a12345D1Santa Monica California Y 12012023 FALL2023
预期结果
B08a12345D1Santa Monica California (filler 15 charcters) Y120120212023
创建数据对象集合,无需填充空格。要求您的收藏可以通过
$collection | Out-GridView
正确显示行和列。
使用
$collection | Format-Table | Out-File
导出到文件
样品:
Get-Process | Format-Table -Wrap:$false | Out-File -FilePath S:\scripts\ft.txt
<#
File contents:
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
434 30 34848 75760 23,47 20428 1 AdskAccessCore
453 103 11320 26120 6300 0 AdskAccessServiceHost
739 36 39460 153308 27,80 19528 1 AdskAccessUIHost
657 29 53640 149628 0,34 20512 1 AdskAccessUIHost
#>