简单ForEach结合If Statment带来错误结果

时间:2015-09-30 22:57:40

标签: windows loops powershell foreach

我是PS的新手,我试图执行一个简单的任务,通过使用get-content获取计算机列表,而不是foreach循环对列表中的每个设备执行wmi查询并获得操作系统类型,使用IF语句检查执行不同的任务取决于操作系统,永远赢得vista 7 8 10需要从xp分离。 我写了以下PS脚本:

$computers=Get-Content C:\ComputerList\Computers.txt 
$OSType=Get-WmiObject -Class Win32_operatingsystem -namespace "root\CIMV2" -ComputerName $computers  


ForEach ( $compdevice in $computers ) {

if ( $OSType.buildnumber -eq "2600*" ) {

Write-Host $compdevice"'s OS type is XP" }

Else  {

Write-Host $compdevice"'s Os type is Newer than xp"

 }
   }

在这种情况下,我得到了所有计算机的相同结果(我在域环境中运行秘密2赢得xp 1赢7和1赢8。

我也尝试了不同的变体:

$computers=Get-Content C:\ComputerList\Computers.txt 
$OSType=Get-WmiObject -Class Win32_operatingsystem -namespace "root\CIMV2" -ComputerName $computers  


ForEach ( $compdevice in $computers ) {

if ( $OSType.buildnumber -eq "2600*" ) {

Write-Host $compdevice"'s OS type is XP" }

Else  {

Write-Host $compdevice"'s Os type is Newer than xp"

 }
   }

在这两种情况下,我都得到完全相同的结果(全部转到IF语句的一个选项)

我想知道,我做错了什么? 注意 - 我试图按标题,buildnumber和版本进行过滤。甚至IF语句中的外卡,它都不能正常工作

1 个答案:

答案 0 :(得分:1)

A couple of things are wrong. First, you have captured wmi content into an array but you do not have a relation of that data to computername. If you include wmi lookup inside the foreach loop, then you have the relationship established. In other words:

$computers=Get-Content C:\ComputerList\Computers.txt 

ForEach ( $compdevice in $computers ) {

$OSType=Get-WmiObject -Class Win32_operatingsystem -namespace "root\CIMV2" -ComputerName $compdevice

### you are using '-eq' so you should provide the actual number, you would use * with -like operator
if ( $OSType.buildnumber -eq "2600" ) {
...