2014-12-02 115 views
1

我已经接管了一些已经离开的人的代码,并且想知道前面的人在下面的代码中写的[0]是什么意思?在这段代码中做什么[0]?

我的意思是,他写了:

$os = (Get-WmiObject -computername $hostfqdn -class Win32_OperatingSystem -credential $credential) 
$ostitle = @($os)[0].Caption+" SP"[email protected]($os)[0].ServicePackMajorVersion+"."[email protected]($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"[email protected]($os)[0].ServicePackMajorVersion+"."[email protected]($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 
     } 
    } 
+0

@()是一个数组,[0]让你与索引为0的项目数组中如此例如用于阵列'@(1,2)''$ (1,2)[0]' - > 1,'$(1,2)[1]' - > 2如果你的数组只有1个项目它没有关系 – Paul 2014-12-02 15:49:04

+0

也许它是一个数组下标并处理多个操作系统安装在一台机器上。 – 2014-12-02 15:49:06

回答

3

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

他应该只使用了$os

+0

想到这一点,但是特定的WMI正在请求在特定系统上运行的操作系统。 – 2014-12-02 15:52:32

+0

对于特定情况为真 – Paul 2014-12-02 16:02:12

+0

感谢米奇。 – lara400 2014-12-02 16:19:00