这个代码中的[0]是做什么的?

时间:2014-12-02 15:41:57

标签: powershell

我从已经离开的人手中接过了一些代码,并且想知道下面代码中的[0]意味着什么?

我的意思是,他写道:

$os = (Get-WmiObject -computername $hostfqdn -class Win32_OperatingSystem -credential $credential)
$ostitle   = @($os)[0].Caption+" SP"+@($os)[0].ServicePackMajorVersion+"."+@($os)[0].ServicePackMinorVersion

但是,如果我尝试以下操作,我得到的结果与我在

中添加[0]相同
PS C:\> $os = (Get-WmiObject -computername SERVER-class Win32_OperatingSystem)
PS C:\> @($os)[0].Caption
Microsoft Windows Server 2008 R2 Enterprise

使用[0]:

PS C:\> @($os).Caption
Microsoft Windows Server 2008 R2 Enterprise

整个功能是:

function getoperatingsystem([string]$hostfqdn, [object]$credential, [int]$serverid)
    {
        try {    
            $os = (Get-WmiObject -computername $hostfqdn -class Win32_OperatingSystem -credential $credential)
            $ostitle   = @($os)[0].Caption+" SP"+@($os)[0].ServicePackMajorVersion+"."+@($os)[0].ServicePackMinorVersion
            UpdateRecord "UPDATE t_server SET os='$ostitle' WHERE serverid=$serverid"
        } catch [Exception] {
            $errmsg = $error[0]        
            $currentuser = [Environment]::UserName
            $datetimestamp  = get-date
            writelog "$datetimestamp,$currentuser,[getoperatingsystem],$hostfqdn,$errmsg"
            $error.clear()
            return $false
        }
    }

1 个答案:

答案 0 :(得分:3)

@($os)[0]意味着他正在使用一个元素动态创建一个数组,并且他正在使用[0](数组中的索引)访问数组的第一个元素。

他应该使用$os

相关问题