条件无法匹配

时间:2015-07-13 20:14:47

标签: powershell if-statement

基本上,我尝试读取BIOS设置然后使用if条件,如果匹配则执行另一个命令。

它适用于其他变量,它就是这个变量。

#This Script will check for VT and VTD on Lenovo machines and enable them
#if the current value is disabled. 
#Run Set-ExecutionPolicy Unrestricted first.
#Run As administrator

#Check the current values
$VT= gwmi -class Lenovo_BiosSetting -namespace root\wmi |
     Where-Object {$_.CurrentSetting.split(",",[StringSplitOptions]::RemoveEmptyEntries) -eq "VirtualizationTechnology"} |
     Format-List CurrentSetting
$VTD= gwmi -class Lenovo_BiosSetting -namespace root\wmi |
      Where-Object {$_.CurrentSetting.split(",",[StringSplitOptions]::RemoveEmptyEntries) -eq "VTdFeature"} |
      Format-List CurrentSetting

#Modify the values
#$EnabledVT= (gwmi -class Lenovo_SetBiosSetting -namespace root\wmi).SetBiosSetting("VirtualizationTechnology,Enable")
#$EnableVTD= (gwmi -class Lenovo_SetBiosSetting -namespace root\wmi).SetBiosSetting("VTdFeature,Enable")
#$SaveBios=(gwmi -class Lenovo_SaveBiosSettings -namespace root\wmi).SaveBiosSettings()

#Check if VT is disabled and enable it if it is. 
Echo "Virtualization current settings are below"
Write-output $VT
IF ($VT -like "*Disable*") {
  "this is not working"
} else {
  "Setting is already set to enabled, no changes made."
}

#Check if VTD is disabled and enable it if it is. 
Write-output $VTD
IF ($VTD -like "*,Disable") {
  this is not working
} else {
  "Setting is already set to enabled, no changes made."
}

#Save bios settings.
$SaveBios

Write-host "Check completed, Please restart computer for changes to take effect if any changes were made. "

我尝试过不同的条件来完全匹配或匹配,但似乎没有任何东西可以找到任何东西。

2 个答案:

答案 0 :(得分:4)

所以,这就是你遇到的问题。您将命令的输出传递给Format-List,并将该信息存储在变量中。不要这样做。应使用Format-* cmdlet格式化输出到控制台的内容,而不是用于存储数据以供以后使用。而是删除该部分,然后引用该对象的CurrentSetting属性。

$VT= gwmi -class Lenovo_BiosSetting -namespace root\wmi | Where-Object {$_.CurrentSetting.split(“,”,[StringSplitOptions]::RemoveEmptyEntries) -eq “VirtualizationTechnology”}
$VTD= gwmi -class Lenovo_BiosSetting -namespace root\wmi | Where-Object {$_.CurrentSetting.split(“,”,[StringSplitOptions]::RemoveEmptyEntries) -eq “VTdFeature”}

IF ($VT.CurrentSetting -like "*Disable*") {"this is now working"}
    else {"Setting is already set to enabled, no changes made."}

这将按照需要运作。

答案 1 :(得分:3)

而不是Format-List,请使用Select-Object -ExpandProperty

$VT  = gwmi -class Lenovo_BiosSetting -namespace root\wmi | Where-Object {$_.CurrentSetting.split(“,”,[StringSplitOptions]::RemoveEmptyEntries) -eq “VirtualizationTechnology”} | Select-Object -ExpandProperty CurrentSetting
$VTD = gwmi -class Lenovo_BiosSetting -namespace root\wmi | Where-Object {$_.CurrentSetting.split(“,”,[StringSplitOptions]::RemoveEmptyEntries) -eq “VTdFeature”} | Select-Object -ExpandProperty CurrentSetting