Powershell脚本-仅以管理员身份运行某些命令,其余脚本以非管理员身份运行

时间:2020-05-12 06:58:50

标签: powershell runas

我想要实现的是:我有一个庞大的脚本,为myPC做很多功能。所有这些功能例如在执行时都希望没有管理员权限。运行应用程序“ outlook”等。脚本中只有一个功能(2个命令)需要管理员权限。是否可以仅将这两个命令作为新的Powershell Adminwindow运行并关闭?

$TouchScreen = Get-PnpDevice -FriendlyName 'HID-Compliant Touch Screen'
if ( $TouchScreen.Status -eq 'OK' ) { $TouchScreen | Disable-PnpDevice -confirm:$false } else { $TouchScreen | Enable-PnpDevice -confirm:$false }

我尝试了几件事,但无济于事。启动进程powershell的-命令-Verb runAs -ArgumentList“ -noexit”,“-命令XXX”不接受变量。我在做错什么吗?

一些尝试:

Start-Process powershell -Verb runAs -ArgumentList "-noexit","-command { [string]$TouchScreen = Get-PnpDevice -FriendlyName 'HID-Compliant Touch Screen'; write-host 'testing $TouchScreen';  if ( $TouchScreen.Status -eq 'OK' ) { $TouchScreen | Disable-PnpDevice -confirm:$false } else { $TouchScreen | Enable-PnpDevice -confirm:$false }}"

任何人和所有帮助将不胜感激

P.S:独立脚本的以下几行有效。因为它只是以管理员身份运行当前脚本。但是,正如我之前提到的,这不是我的选择。此外,不想在这里调用其他脚本,原因是我要使用PS2EXE,而其他脚本将成为问题。

If (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
                $Arguments = "& '" + $MyInvocation.mycommand.definition +"'" 
                Start-Process powershell -Verb runAs -ArgumentList $Arguments 
                Break
                }
                $TouchScreen = Get-PnpDevice -FriendlyName 'HID-Compliant Touch Screen'
                if ( $TouchScreen.Status -eq 'OK' ) { $TouchScreen | Disable-PnpDevice -confirm:$false } else { $TouchScreen | Enable-PnpDevice -confirm:$false }

1 个答案:

答案 0 :(得分:0)

以这种方式解决

$MyVar = {"$TouchScreen = Get-PnpDevice -FriendlyName 'HID-Compliant Touch Screen'";  "if ( $TouchScreen.Status -eq 'OK' ) { $TouchScreen | Disable-PnpDevice -confirm:$false } else { $TouchScreen | Enable-PnpDevice -confirm:$false }";}
Start-Process powershell -Verb runas -ArgumentList "-noexit",$MyVar