将具有对象布局的字符串转换为对象

时间:2019-07-15 10:23:08

标签: powershell

某些对象已保存到txt.file 看起来像这样:

@{flightNumber=01; flightDate=2010-01-10; flightIdentification=201001}
@{flightNumber=01; flightDate=2010-01-10; flightIdentification=201002}

,我正在尝试在另一个程序中读取它们,并将它们转换回对象。令我困扰的是它将每个“对象”都理解为字符串,而我无法将其转换为对象。

$list = Get-Content -Path 'C:\Users\XXXXX\Downloads\TemplateObject.txt'
foreach (@object in $list) {
    Write-Host $object.flightNumber
}

根据我的显示,我希望看到两个不同的对象,它们具有变量flightNumber,flightDate和flightIdentification

  1. 我尝试使用ConvertFrom-StringData对其进行管道传递
  2. 我尝试过投射到对象

我希望有2个单独的对象,每个对象中都包含3个变量。

2 个答案:

答案 0 :(得分:1)

不要将对象直接传输到文件中!

has been pointed out一样,利用内置选项将磁盘序列化,例如ConvertTo-Csv / Export-Csv代表平面对象,ConvertTo-JsonExport-Clixml代表磁盘对象更复杂的对象。


作为一项一次性的工作,如果您需要恢复并重新编码此数据,则可以使用regex -replace运算符在值周围添加引号,此时解析器应将其接受为哈希表条目,然后将其强制转换为对象:

$string = '@{flightNumber=01; flightDate=2010-01-10; flightIdentification=201001}'

# Place double-quotes around anything found between a `=` and `;` or `}`
$quotedString = $string -replace '(?<=\=)([^=;}]+)(?=\s*(?:;|}))', '"$1"'

# Parse the resulting string as if it was PowerShell code
$errors = @()
$objectAST = [System.Management.Automation.Language.Parser]::ParseInput($quotedString, [ref]$null,[ref]$errors)
$objects = if(-not $errors){
    # This is pretty dangerous, you should NEVER do this in a production script
    $objectAST.GetScriptBlock.Invoke() |ForEach-Object {
        [pscustomobject]$_
    }
}

# This variable now contains the re-animated objects
$objects

答案 1 :(得分:0)

您可以在进行一些操作后使用convertfrom-stringdata将字符串转换为哈希表:

$a = '@{flightNumber=01; flightDate=2010-01-10; flightIdentification=201001}'
$a = $a -replace '@{' -replace '}' -replace ';',"`n" | ConvertFrom-StringData
[pscustomobject]$a

flightNumber flightIdentification flightDate
------------ -------------------- ----------
01           201001               2010-01-10