Powershell 将txt转换为对象
我想将此文件的内容(前两列,条形码和位置)转换为对象,但我无法创建对象Powershell 将txt转换为对象,powershell,object,Powershell,Object,我想将此文件的内容(前两列,条形码和位置)转换为对象,但我无法创建对象 #BARCODE LOCATION LIBRARY STATUS COPY #------- -------- ------- ------ ---- #L40001L8 slot 41 DRP_TAPE_DRPLTO Full Primary_Global #L40002L8 slot 96
#BARCODE LOCATION LIBRARY STATUS COPY
#------- -------- ------- ------ ----
#L40001L8 slot 41 DRP_TAPE_DRPLTO Full Primary_Global
#L40002L8 slot 96 DRP_TAPE_DRPLTO Full Primary_Global
#L40034L8 IEPort2 DRP_TAPE_DRPLTO Full Primary_Global
$object= @{}
ForEach ($i in $(gc "C:\temp\tapes.txt"))
{
$object.BARCODE= ($i.ToString().Substring(0,8))
$object.LOCATION= ($i.ToString().Substring(0,19))
New-Object psobject -Property $object
}
有人能帮我吗?使用从哈希表创建对象:
$ht = @{ 'key1' = 'value1'; key2 = 'value2' }
$ht['key3'] = 'value3'
$o = [PSCustomObject]$ht
当您有固定宽度的列时:
$lines = @(@'
#BARCODE LOCATION LIBRARY STATUS COPY
#------- -------- ------- ------ ----
#L40001L8 slot 41 DRP_TAPE_DRPLTO Full Primary_Global
#L40002L8 slot 96 DRP_TAPE_DRPLTO Full Primary_Global
#L40034L8 IEPort2 DRP_TAPE_DRPLTO Full Primary_Global
'@ -split "`r`n" )
# $lines = [System.IO.File]::ReadAllLines($filePath)
$lines = $lines | Select-Object -Skip 2
$objects = $lines | % {
return [PSCustomObject]@{
BARCODE = $_.Substring(1,8).Trim()
LOCATION = $_.Substring(13,8).Trim()
}
}
$objects
首先,该文件的内容看起来非常像您从一个对象数组开始,然后使用
Format Table
对其进行“stringyfied”,并将控制台的输出复制/粘贴到您的文本文件中。
我不知道为什么现在每一行都要在前面加上注释。也许你这样做是为了把问题格式化成这样
我想说的是,如果确实发生了这种情况,那么通过从代码中删除格式表
,并使用类似Export Csv
的cmdlet保存对象数组,或者通过另存为JSON或XML来更改用于创建文件的脚本将更有意义
无论如何,如果您在这方面没有选择,并且需要将该文件转换回对象,则可以执行以下操作:
# read the file line-by-line and replace the whitespaces with a comma
$data = switch -Regex -File 'D:\Test\File1.txt' {
'^#[^-]' { $_.TrimStart("#") -replace '\s+', ',' }
# if the comment marks '#' are NOT in the file, use this instead
# '^[^-]' { $_ -replace '\s+', ',' }
}
$result = $data | ConvertFrom-Csv | Select-Object BARCODE, LOCATION
# output on screen
$result
# output to CSV file
$result | Export-Csv -Path 'D:\Test\Output1.csv' -UseCulture -NoTypeInformation
屏幕上的输出将如下所示
BARCODE LOCATION
------- --------
L40001L8 slot
L40002L8 slot
L40034L8 IEPort2
您只需双击Output1.csv文件即可在Excel中打开>对不起,我写问题的错误。文件中没有任何#。非常感谢,使用“ConvertFrom Csv”让我对其他脚本有了一些想法。再次感谢您的时间Hi filimonic,非常感谢!重写子字符串部分,因为文件没有任何#。工作。谢谢你抽出时间。