标签:powershell 逻辑判断 条件控制
PowerShell条件控制
If, else, elseif 语句
基本语法:
if (条件)
{代码}
elseif (条件)
{代码}
else (条件)
{代码}
else
{代码}
例如1:
$n=10
if ($n -eq 1)
{"n=1"}
elseif ($n -ne 1)
{"n!=1,and n=$n"}
结果:{"n!=1,and n=$n"}
例如2:查看本机的操作系统
$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–"
结果:
Computer1 is not supported.
-END OF REPORT-
PS C:\>
PS C:\> $OS_Version
6.3.9600
Switch 语句
基本语法:
switch (表达式)
{
(表达式) {代码}
值 {代码}
default {默认执行代码}
}
例如,我们可以查询"domainRole"的值来判断计算机在当前ActiveDirectory域中担任的角色,试试下面的代码:
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"}
}
在成员计算机中运行结果:”member workstation”
PowerShell逻辑判断
介绍
-eq 判断是否等于(equal)
-lt 判断时候小于(less than)
-gt 判断是否大于(greater than)
-ge 判断是否大于或等于(greater of equal)
-le 判断是否小于或等于(less or equal)
-ne 判断是否不等于(no equal)
-ieq (case-insensitive) 大小写不敏感,忽略大小写
-ceq (case-sensitive) 大小写敏感
实例
“A” –eq “a” 结果 : true
“A” –ieq “a” 结果 : true
“A” –ceq “a” 结果 : False
逻辑运算
-and 与
-or 或
-not 非
! 非
参考:http://marui.blog.51cto.com/1034148/293907
本文出自 “Ricky's Blog” 博客,请务必保留此出处http://57388.blog.51cto.com/47388/1639194
标签:powershell 逻辑判断 条件控制
原文地址:http://57388.blog.51cto.com/47388/1639194