执行Invoke-expression时,Powershell脚本在运行时退出

时间:2018-07-01 18:54:08

标签: powershell powershell-v3.0

我正在尝试执行以下代码,当运行时达到第一个invoke-expression时,脚本退出,不运行其余代码.ps1文件。这是在带有Powershell v3的Windows 7中发生的。这里的任何指针表示赞赏。我尝试使用Try {Invoke-expression“”} catch {$ _},但日志显示该脚本退出。

    $HardWares=@("abc","def")
    Write-Info ("Deleting device driver with $application")
    foreach ($HardWare in $HardWares){
        Write-Info ("working on hardware $HardWare")
        $DriverID = (Get-WmiObject -Class Win32_PnpSignedDriver | Where-Object {$_.hardwareID -eq $HardWare} | Select-Object InfName -ExpandProperty InfName | Select-Object -Unique)
        if ($DriverID){
            Write-Info ("Removing $HardWare and deleting $DriverID")
            $HardwareRemoveCmd = "D:\Users\App.exe remove $HardWare" 
            Invoke-Expression $HardwareRemoveCmd                              
            $Command= "D:\Users\App.exe dp_delete $DriverID -f"
            Invoke-Expression $Command
        } else {Write-Info "Could not find $DriverID file for $HardWare"}
    }

1 个答案:

答案 0 :(得分:-2)

问题可能是您创建了一个名为$ DriverID的变量,但您正在检查$ Driverid是否返回true。变量创建区分大小写,因此这里有两个不同的变量。这将返回false,导致脚本跳过else语句。

如果要“找不到任何$ Driverid”写入到显示器,则需要在其前面放置“ Write-Host”。

代码的整理版本。

{
    $Driverid = (Get-WmiObject -Class Win32_PnpSignedDriver | Where-Object 
    {$_.hardware -eq $HardWare} | Select-Object InfName -ExpandProperty InfName 
    | Select-Object -Unique)

    if($Driverid)
    {  
        Invoke-Expression "D:\Users\App.exe remove $HardWare" 
        $Command= "D:\Users\App.exe dp_delete $Driverid -f" 
        Invoke-Expression $Command
    }
    else
    {   
        Write-Host "did not find any $Driverid"
    }
}

希望这会有所帮助!