考虑这个函数,它返回一个字符串值表,每行都有两个字符串属性,名称为 DisplayName 和 DisplayVersion:
function Get-InstalledDotNetPacks{
[CmdletBinding()]
Param()
Get-ItemProperty `
-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*", `
"HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" |
Where {$_.DisplayName -like '*.NET*'} |
Select-Object DisplayName, DisplayVersion |
Sort -Property DisplayName
}
如何使用 OutType() 来显示函数将返回的两个属性名称?
class
作为属性包并允许发现这两个属性:
class DotNetPack {
[string] $DisplayName
[string] $DisplayVersion
}
然后你摆脱
Select-Object
因为它会返回 PSCustomObject
并将其替换为你的类的实例:
class DotNetPack {
[string] $DisplayName
[string] $DisplayVersion
}
function Get-InstalledDotNetPacks {
[OutputType([DotNetPack])]
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()]
[string[]] $Path = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
)
Get-ItemProperty -Path $Path |
Where-Object { $_.DisplayName -like '*.NET*' } |
Sort-Object -Property DisplayName |
ForEach-Object {
[DotNetPack]@{
DisplayName = $_.DisplayName
DisplayVersion = $_.DisplayVersion
}
}
}
完成后工作正常: