我下面的函数将创建一个HTML表,但是我希望表中的值具有超链接。
Function MyFunction{
clear-host
$item=$null
$hash = $null #hashTable
$hash =@{"Google.com" = "www.google.com"; "Yahoo" = "www.yahoo.com";"My Directory" ="C:\Users\Public\Favorites" ;"MSN" = "www.msn.com"}
ForEach($item in @($hash.KEYS.GetEnumerator())){
$hash | Sort-Object -Property name
}
$hash.GetEnumerator() | sort -Property Name |Select-Object Name, Value | ConvertTo-HTML | Out-File .\Test.html
}
MyFunction
Run Code Online (Sandbox Code Playgroud)
在开始之前,请注意一点:ForEach似乎毫无意义,因为它只输出表中每个元素的排序表。这样就删除了。
ConvertTo-HTML它本身非常适合使用PowerShell对象制作表,但是我们需要的是超链接。ConvertTo-HTML确实支持计算的属性,因此乍一看,仅制作格式化的超链接似乎很容易。
ConvertTo-HTML -Property *,@{Label="Link";Expression={"<a href='$($_.Value)'>$($_.Name)</a>"}}
Run Code Online (Sandbox Code Playgroud)
这样做的一个小问题是ConvertTo-Html,对发送给它的字符串进行了一些转换,这使我们的意图难以理解。在创建的输出文件中,我们看到以下Yahoo链接:
<td><a href='www.yahoo.com'>Yahoo</a></td>
Run Code Online (Sandbox Code Playgroud)
ConvertTo-Html使我们的文本浏览器友好,这通常会很好,但现在却妨碍了我们。从PowerShell Magazine阅读博客可解决此问题,方法是在将html发送到文件之前对其进行解码。
Function MyFunction{
clear-host
$hash = @{"Google.com" = "www.google.com"; "Yahoo" = "www.yahoo.com";"My Directory" ="C:\Users\Public\Favorites" ;"MSN" = "www.msn.com"}
$hash.GetEnumerator() | sort -Property Name | Select-Object Name, Value |
ConvertTo-HTML -Property *,@{Label="Link";Expression={"<a href='$($_.Value)'>$($_.Name)</a>"}}
}
$html = MyFunction
Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlDecode($html) | Out-File C:\temp\test.html
Run Code Online (Sandbox Code Playgroud)
使用[System.Web.HttpUtility]::HtmlDecode可以将值转换<回我们想要的值。看一下输出

想看看是否曾经有人问过这个问题,并且有一个类似的答案:如何在Powershell中的目录中生成指向.htm文件的超链接?。它以不同的方式进行处理,因此在将其标记为重复项时会在围墙上。
| 归档时间: |
|
| 查看次数: |
6688 次 |
| 最近记录: |