我有以下代码:
$xmlFile = 'C:\Users\kraer\Desktop\bom.xml'
[xml]$xml = Get-Content $xmlFile
$xml.bom.components.component | ForEach-Object {
$finalObject = [PSCustomObject]@{
'Name' = $_.name
'Version' = $_.version
'License' = $_.licenses.license.id
}
Write-Output $finalObject
}
现在我想将 $finalObject 转换为 MarkDown 表。这里还有什么可能性吗?
对于另一个问题,我收到了这个答案,但现在它不适用于我的代码。
function ConvertTo-MarkDownTable {
[CmdletBinding()] param(
[Parameter(Position = 0, ValueFromPipeLine = $True)] $InputObject
)
Begin { $Init = $True }
Process {
if ( $Init ) {
$Init = $False
$_.PSObject.Properties.Name -Join '|'
$_.PSObject.Properties.ForEach({ '-' }) -Join '|'
}
$_.PSObject.Properties.Value -Join '|'
}
}
您还有其他解决方案吗?
感谢您的帮助
不知道 bom.xml 的内容,您可以尝试这个稍微修改过的函数版本:
function ConvertTo-MarkDownTable {
[CmdletBinding()] param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
$InputObject
)
Begin {
$headersDone = $false
$pattern = '(?<!\\)\|' # escape every '|' unless already escaped
}
Process {
if (!$headersDone) {
$headersDone = $true
# output the header line and below that a dashed line
# -replace '(?<!\\)\|', '\|' escapes every '|' unless already escaped
'|{0}|' -f (($_.PSObject.Properties.Name -replace $pattern, '\|') -join '|')
'|{0}|' -f (($_.PSObject.Properties.Name -replace '.', '-') -join '|')
}
'|{0}|' -f (($_.PsObject.Properties.Value -replace $pattern, '\|') -join '|')
}
}
Usage:
# load the xml from file
$xml= New-Object System.XML.XMLDocument
$xml.Load('C:\Users\kraer\Desktop\bom.xml')
$finalObject = $xml.bom.components.component | ForEach-Object {
[PSCustomObject]@{
'Name' = $_.name
'Version' = $_.version
'License' = $_.licenses.license.id
}
}
# convert to markdown
$finalObject | ConvertTo-MarkDownTable
P.S. $_.licenses.license.id
可能是错的,因为它看起来像licenses
is an array的许可证。您可能想在这里做这样的事情:
($_.licenses | ForEach-Object { $_.license.id }) -join '; '
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)