繁体   English   中英

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

[英]Powershell Script - Run certain commands only as admin and rest of script as non-admin

我想要实现的是:我有一个巨大的脚本,它为 myPC 执行了很多功能。 所有这些 function 在执行例如运行应用程序“outlook”等时都希望没有管理员权限。脚本中只有一个 function(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 }

我尝试了几件事,但无济于事。 Start-Process powershell -Verb runAs -ArgumentList "-noexit","-command XXX" 的 -command 不接受变量。 难道我做错了什么?

一些尝试:

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 }}"

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

PS:独立脚本的以下行有效。 因为它只是以管理员身份运行当前脚本。 但正如我之前提到的,这对我来说不是一个选择。 此外,不打算在这里调用其他脚本,原因是我将使用 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 }

这样解决了

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM