我正在尝试创建一个函数来生成无序的HTML列表。当我像ConvertTo-HTMLlist $MyArray
一样使用它时,它可以正常工作,但是当我像$MyArray | ConvertTo-HTMLlist
那样将信息通过管道传输给它时,这种方法就可以正常工作。
我的功能:
Function ConvertTo-HTMLlist {
[CmdletBinding(SupportsShouldProcess=$True)]
Param (
[parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
$Array
)
Process {
$Array = @(foreach ($_ in $Array) {"<li>" + $_ + "<br><br></li>"}) # Add extra space
$Array = ,"<ul>$($Array | Sort-Object)</ul>"
$Array = $Array.Replace("<br><br></li></ul>", "</li></ul>") # Remove last double breaks
$Array += "<p><i><font size=`"2`">* Native PowerShell errors are displayed in <font color=`"red`">red</font>.</font></i></p>"
Write-Output $Array
}
}
结果:
$MyArray = 'Apples', 'Peers', 'Bananas'
ConvertTo-HTMLlist $MyArray
# Correct result:
<ul><li>Apples<br><br></li> <li>Bananas<br><br></li> <li>Peers</li></ul><p><i><font size="2">* Native PowerShell errors are displayed in <font color="red">red</font>.</f
ont></i></p>
$MyArray | ConvertTo-HTMLlist
# Incorrect result:
<ul><li>Apples</li></ul><p><i><font size="2">* Native PowerShell errors are displayed in <font color="red">red</font>.</font></i></p>
<ul><li>Peers</li></ul><p><i><font size="2">* Native PowerShell errors are displayed in <font color="red">red</font>.</font></i></p>
<ul><li>Bananas</li></ul><p><i><font size="2">* Native PowerShell errors are displayed in <font color="red">red</font>.</font></i></p>
应该有一种方法可以首先从管道中收集所有内容,然后开始处理它。
最佳答案
因为在PowerShell中一切皆有可能,所以我在函数中的Begin
,Process
和End
子句中做了更多的工作。而且我认为我已经按照要求工作了:
$MyArray = 'Apples', 'Peers', 'Bananas'
Function ConvertTo-HTMLlist {
[CmdletBinding(SupportsShouldProcess=$True)]
Param (
[parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
$Array
)
Begin {
$tmpArray = New-Object System.Collections.ArrayList
}
Process {
$Array | ForEach-Object {
$tmpArray.Add("<li>" + $_ + "<br><br></li>") | Out-Null
}
}
End {
$tmpArray = ,"<ul>$($tmpArray | Sort-Object)</ul>"
$tmpArray = $tmpArray.Replace("<br><br></li></ul>", "</li></ul>") # Remove last double breaks
$tmpArray += "<p><i><font size=`"2`">* Native PowerShell errors are displayed in <font color=`"red`">red</font>.</font></i></p>"
Write-Output $tmpArray
}
}
Write-Host "Piped result:" -ForegroundColor Yellow
$MyArray | ConvertTo-HTMLlist
Write-Host "Non piped result:" -ForegroundColor Yellow
ConvertTo-HTMLlist $MyArray
让我知道你的想法。