如何获得一个类的所有实例?

时间:2019-08-06 07:37:40

标签: powershell

我对班级的了解相对较新。但是我想用powershell输出类的所有对象/实例。这有可能吗?这是我如何创建计算机类的两个对象的示例。

Class Computer {
    [String]$Name
    [String]$Description
    [String]$Type

}

$NewComputer = New-Object 'Computer'
$NewComputer.Name = 'ultra1'
$NewComputer.Description = 'Lenovo Yoga 900'
$NewComputer.Type = 'Ultrabook' 

$NewComputer = New-Object 'Computer'
$NewComputer.Name = 'ultra2'
$NewComputer.Description = 'Lenovo Yoga X1'
$NewComputer.Type = 'Ultrabook' 

现在我要输出两个对象,该怎么做?

3 个答案:

答案 0 :(得分:0)

也许这会有所帮助

Class Computer {
    [String]$Name
    [String]$Description
    [String]$Type

}

# a collection of computers
$computers =@()

$NewComputer = New-Object 'Computer'
$NewComputer.Name = ‘ultra1’
$NewComputer.Description = ‘Lenovo Yoga 900’
$NewComputer.Type = ‘Ultrabook’ 

# append a computer to teh collection
$computers += $NewComputer

$NewComputer = New-Object 'Computer'
$NewComputer.Name = ‘ultra2’
$NewComputer.Description = ‘Lenovo Yoga X1’
$NewComputer.Type = ‘Ultrabook’ 

# append a computer to teh collection
$computers += $NewComputer

# this outputs each of the computers
$computers

# or you can format the data in a table
$computers | Format-Table -AutoSize

# or in a list
$computers | Format-List *

# or as json
$computers | ConvertTo-Json

答案 1 :(得分:0)

从您的评论判断“如果有可能在不将其放入集合的情况下获取类的对象” ,我认为您想要做的是创建新的{{1} }对象,然后再使用这些类作为单独的变量。

为了便于创建,我建议您在类中添加一个constructor,以便可以在一行中创建对象:

Computer

输出:

Class Computer {
    [String]$Name
    [String]$Description
    [String]$Type

    # add a constructor
    Computer(
        [string]$n,
        [string]$d,
        [string]$t
    ){
        $this.Name = $n
        $this.Description = $d
        $this.Type = $t
    }
}

# now create the computer objects
[Computer]$pcUltra1 = [Computer]::new('ultra1','Lenovo Yoga 900','Ultrabook')
[Computer]$pcUltra2 = [Computer]::new('ultra2','Lenovo Yoga X1','Ultrabook')

# show what you have now
$pcUltra1
$pcUltra2

希望有帮助

答案 2 :(得分:0)

假设您没有重新绑定任何名称,则可以执行以下操作:

Get-Variable | Select-Object -ExpandProperty Value |
    Where-Object { $_.GetType().Name -eq 'Computer' }