PowerShell脚本不引用存储在变量中的值

时间:2018-02-01 21:01:40

标签: powershell

我在让脚本在整个脚本中使用$computername变量中存储的值时遇到问题。此值用于在网络上的远程计算机上运行命令。该脚本仅使用存储在变量中的值一次,但后续的两个if else命令在本地计算机而不是远程计算机上运行。

这里是.ps1脚本:

$computername = Read-Host "What computer do you want to check hibernation status for?"
Invoke-Command -Computer $computername {
    Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Power -Name HibernateEnabled
}

$hiberstatus = Read-Host "Would you like to change hibernation status for this machine? Use 'y' for Yes and 'n' for No."

if ($hiberstatus -eq 'y') {
    $hiberchange = Read-Host "Would you like to enable or disable hibernation? Use 'en' for enable and 'dis' for disable."
    if ($hiberchange -eq 'en') {
        Enter-PSSession $computername
        powershell -Command "Start-Process 'powercfg.exe' -Verb runAs -Argumentlist '/h on'"
        Exit-PSSession
    } elseif ($hiberchange -eq 'dis') {
        Enter-PSSession $computername
        powershell -Command "Start-Process 'powercfg.exe' -Verb runAs -Argumentlist '/h off'"
        Exit-PSSession
    }
} elseif ($hiberstatus -eq 'n') {
    exit
}

$hiberupdate = Read-Host "Would you like to confirm the changes made? Use 'y' for Yes and 'n' for No."

if ($hiberupdate -eq 'y') {
    Invoke-Command -Computer $computername {
        Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Power -Name HibernateEnabled
    }
} elseif ($hiberupdate -eq 'n') {
    Write-Output 'Terminating powercfg sessions!'
}

1 个答案:

答案 0 :(得分:0)

我将如何做到这一点:

if ($hiberstatus -eq 'y') {
    $hiberchange = Read-Host "Would you like to enable or disable hibernation? Use 'en' for enable and 'dis' for disable."
    if ($hiberchange -eq 'en') {
        Invoke-Command $ComputerName {"Start-Process 'powercfg.exe' -Verb runAs -Argumentlist '/h on'"}
    } elseif ($hiberchange -eq 'dis') {
        Invoke-Command $ComputerName {"Start-Process 'powercfg.exe' -Verb runAs -Argumentlist '/h off'"}
    }
} elseif ($hiberstatus -eq 'n') {
    exit
}