Reputation: 629
I'm currently creating an AD script that can get the AD groups of one machine and transfer them to a new machine (in case of system failure).
I've managed to get the script to go out and find the versions of Windows that the two machines are running via their hostname, however I'm having a problem creating an 'if' statement to compare the two versions of Windows.
The idea is that if the are the same version (and thus the same package version) the groups will be copied automatically, but I can't for the life of me figure out how to do it.
Please consider this code:
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"
}
}
Now is it true that all variables cannot be accessed outside of functions?
If so, what else can I do?
Upvotes: 1
Views: 13529
Reputation: 3494
Probably what you're missing is that with PowerShell order of operations, you often have to put function calls in parentheses.
Try this instead:
if ((W_version_current) -eq (W_version_target))
{
"Matching version of Windows detected"
}
else
{
"Versions of Windows do not match"
}
To answer your question, scope in PowerShell works pretty much like most other scripting languages, e.g. variables declared in functions cannot be used outside of the functions they were declared, unless you declare them as global, which you can do like so:
$global:x = "hi"
You can then use the variable $x
anywhere, or if you like, $global:x
, and it will have the value of "hi"
.
Upvotes: 1