【问题标题】:Powershell Script - Run certain commands only as admin and rest of script as non-adminPowershell 脚本 - 仅以管理员身份运行某些命令,其余脚本以非管理员身份运行
【发布时间】:2020-05-12 06:58:50
【问题描述】:

我想要实现的是:我有一个巨大的脚本,可以为 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 }

我尝试了几件事,但无济于事。 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 }}"

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

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 }

【问题讨论】:

    标签: powershell runas


    【解决方案1】:

    这样解决了

    $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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 2022-01-08
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多