在嵌套PSObject属性上重载ToString的问题

时间:2018-08-28 01:07:12

标签: powershell overloading psobject get-wmiobject

我创建了一个具有各种属性的自定义PSObject,并且尝试对其中的一些属性重载ToString。我已经成功使用了TimeSpan属性之一,但是没有一个WMI对象。

# Get WMI info
$wmiOS = Get-WmiObject -Class Win32_OperatingSystem
$wmiSystem = Get-WmiObject -Class Win32_ComputerSystem
$wmiDrives = Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType='3'"
$ipv4Address = (Test-Connection -ComputerName $env:COMPUTERNAME -Count 1).IPV4Address.IPAddressToString
$uptime = (Get-Date) - ($wmiOS.ConvertToDateTime($wmiOS.LastBootUpTime))
# Setup object
$result = New-Object -TypeName psobject -Property @{
    Hostname = $($wmiSystem.Name)
    Domain = $($wmiSystem.Domain)
    Username = $($wmiSystem.Username)
    OperatingSystem = $($wmiOS.Caption)
    OSArchitecture = $($wmiOS.OSArchitecture)
    PSVersion = "$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor)"
    IPv4Address = $ipv4Address
    Uptime = $uptime
    DriveInfo = $wmiDrives
}

# Overload DriveInfo ToString
$result.DriveInfo = $result.DriveInfo | Add-Member -MemberType ScriptMethod -Name ToString -Value {
    "$($this.DeviceID) $($this.FreeSpace) GB;"
} -Force -PassThru

# Overload Uptime ToString 
$result.Uptime = $result.Uptime | Add-Member -MemberType ScriptMethod -Name ToString -Value {
    "$($this.Days) days, $($this.Hours) hours, $($this.Minutes) minutes, $($this.Seconds) seconds"
} -Force -PassThru

# Overload result ToString
$result = $result | Add-Member -MemberType ScriptMethod -Name ToString -Value {
    $temp = @"
Hostname: $($this.Hostname)
Domain: $($this.Domain)
Console User: $($this.Username)
Operating System: $($this.OperatingSystem)
OS Architecture: $($this.OSArchitecture)
PS Version: $($this.PSVersion)
IPv4 Address: $($this.IPv4Address)
Uptime: $($this.Uptime.ToString())
Free Space: $($this.DriveInfo)
"@
        $temp
    } -Force -PassThru

一切似乎都正常,但DriveInfo超载。我只是得到“ System.Object []”作为返回。对我来说奇怪的是,当我只执行$ result.ToString()时,我得到以下信息(请参见“可用空间”):

Domain: domain.local
Console User: domain\username
Operating System: Microsoft Windows 10 Pro
OS Architecture: 64-bit
PS Version: 5.1
IPv4 Address: 1.1.1.1
Uptime: 2 days, 1 hours, 31 minutes, 49 seconds
Free Space: C: 58721181696; E: 631496687616;

$ result.Uptime.ToString():

2 days, 1 hours, 19 minutes, 34 seconds

$ result.DriveInfo.ToString():

System.Object[]

我可能缺少明显的东西,但此时我迷路了。感谢您可以提前提供的帮助!

1 个答案:

答案 0 :(得分:0)

您能不能尝试替换:

$result.DriveInfo = $result.DriveInfo | Add-Member -MemberType ScriptMethod -Name ToString -Value {"$($this.DeviceID) $($this.FreeSpace) GB;"} -Force -PassThru

通过

$result.DriveInfo | Add-Member -MemberType ScriptMethod -Name ToString -Value {"$($this.DeviceID) $($this.FreeSpace) GB;"} -Force -PassThru

据我了解,Add-Member适用于每个驱动器,您无需影响结果,因为您可以更改列表中的每个对象。之后,您可以使用:

$n = 0
$result.DriveInfo[$n].ToString()