我已經接管了一些已經離開的人的代碼,並且想知道前面的人在下面的代碼中寫的[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的項目數組中如此例如用於陣列'@(1,2)''$ (1,2)[0]' - > 1,'$(1,2)[1]' - > 2如果你的數組只有1個項目它沒有關係 – Paul 2014-12-02 15:49:04
也許它是一個數組下標並處理多個操作系統安裝在一臺機器上。 – 2014-12-02 15:49:06