2014-12-02 118 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