If, Else, ElseIf statement
Basic syntax:
if ( condition )
{ Code }
ElseIf ( condition )
{ Code }
Else ( conditional )
{ Code }
Else
{ Code }
For example 1:
$n =10
if ($n-eq 1)
{"N=1"}
ElseIf ($n-ne 1)
{"N!=1,and n= $n"}
Results: {"N!=1,and n= $n"}
Example 2: View the operating system of this computer
$ComputerName = (Get-wmiobject-class win32_computersystem). Name
$OS _version = (Get-wmiobject-class win32_operatingsystem-computer$computername). Version
if (($OS _version-eq "5.1.2600")-or ($OS _version-eq "5.2.3790"))
{
Write-host "ComputerName:" $ComputerName
if ($OS _version-eq "5.1.2600")
{
Write-host "Os:windowsxp"
}
ElseIf ($OS _version-eq "5.2.3790")
{
Write-host "os:windows2003"
}
}
ElseIf (($OS _version-eq "5.0.2195")-or ($OS _version-eq "6.1.7600"))
{
Write-host "ComputerName:" $ComputerName
if ($OS _version-eq "5.0.2195")
{
Write-host "os:windows2000 Server"
}
ElseIf ($OS _version-eq "6.1.7600")
{
Write-host "Os:windows7"
}
}
Else
{
Write-host "$ComputerNameis not supported."
}
"–end of report–"
Results:
Computer1 is not supported.
-end of report-
PS c:\>
PS c:\> $OS _version
6.3.9600
Switch Statement
Basic syntax:
Switch ( expression )
{
( expression ) { Code }
value { code }
Default { execution code }
}
For example , we can query the value of "DomainRole" to determine the role that the computer holds in the current activedirectory domain, try the following code:
Switch ((Get-wmiobject-class win32_computersystem). DomainRole)
{
0 {write-host "standaloneworkstation"}
1 {write-host "Memberworkstation"}
2 {write-host "Standaloneserver"}
3 {write-host "Memberserver"}
4 {write-host "Backup DomainController"}
5 {write-host "Primarydomain Controller"}
Default {write-host "Cannotdetermine domain Role"}
}