2012-04-19 28 views
1

我目前正在創建一個AD腳本,可以獲取一臺機器的AD組並將它們傳輸到新機器(以防系統故障)。使用PowerShell'如果'語句來比較功能(Windows版本)

我設法讓腳本出去找到兩臺機器通過主機名運行的Windows版本,但是我在創建'if'語句來比較兩個版本的視窗。

這個想法是,如果是相同的版本(並因此相同的軟件包版本),這些組將自動複製,但我不能爲我的生活弄清楚如何做到這一點。

請考慮下面的代碼:

function W_version_current 
{ 
    $current = Get-WmiObject Win32_OperatingSystem -computer $current_hostname.text | select buildnumber 
    if ($current -match '7601') 
    { 
     "Windows 7" 
    } 
    elseif($current -match '2600') 
    { 
     "Windows XP" 
    } 
    elseif($current -eq $null) 
    { 
     "The box is empty" 
    } 
    else 
    { 
     "Function not supported" 
    } 
} 

function W_version_target 
{ 
    $target = Get-WmiObject Win32_OperatingSystem -computer $target_hostname.text | select buildnumber 
    if ($var -match '7601') 
    { 
     "Windows 7" 
    } 
    elseif($target -match '2600') 
    { 
     "Windows XP" 
    } 
    elseif($target -eq $null) 
    { 
     "The box is empty" 
    } 
    else 
    { 
     "Function not supported" 
    } 
} 

function compare_current_target 
{ 
    if(W_version_current -eq W_version_target) 
    { 
     "Matching version of Windows detected" 
    } 
    else 
    { 
     "Versions of Windows do not match" 
    } 
} 

現在是真的,所有的變量不能在函數外進行訪問?

如果是這樣,我還能做什麼?

回答

0

您可能錯過的是,使用PowerShell操作順序時,您經常必須將函數調用放在括號內。

試試這個:

if ((W_version_current) -eq (W_version_target)) 
{ 
    "Matching version of Windows detected" 
} 
else 
{ 
    "Versions of Windows do not match" 
} 

要回答你的問題,範圍在PowerShell中的工作非常像大多數其他腳本語言,例如函數聲明的變量不能的,他們宣稱,除非你聲明爲全局,你可以做像這樣的功能,外部使用:

$global:x = "hi" 

然後,您可以使用變量$x任何地方,或者如果你喜歡, $global:x,它將具有值"hi"

+0

那麼這是否意味着$ global:X =「hi」 - X是一個具有高值的全局變量? – obious 2012-04-21 18:47:56

+0

答案更新:) – Nacht 2012-04-22 05:24:23

+0

我會建議只是玩弄它 - 你會弄清楚它是如何工作很快 – Nacht 2012-04-22 05:25:01