如何使用管理员权限运行脚本以更改执行策略

时间:2016-06-11 17:17:10

标签: powershell admin

见下面的脚本: 我需要启动此脚本,并在脚本中嵌入管理员权限,将执行策略设置为不受限制,然后在脚本结束时将其设置回来。从我到目前为止发现的情况来看,这是不可能的,也可能是非常困难的。我希望有一种更简单的方法来做到这一点。将运行此脚本的用户在其PC上没有管理员权限,因此他们将无法从powershell内部提升和手动运行。

Stop-process -Name OUTLOOK -ErrorAction SilentlyContinue -Force
Stop-process -Name communicator -ErrorAction SilentlyContinue -Force
Stop-process -Name lync -ErrorAction SilentlyContinue -Force
Stop-Process -Name UcMapi -ErrorAction SilentlyContinue -Force
Stop-Process -Name skypehost -ErrorAction SilentlyContinue -Force
Stop-Process -Name searchprotocolhost -ErrorAction SilentlyContinue -Force

$OstPath = "c:\users\$([environment]::username)"+ "\AppData" + "\local" + "\Microsoft" + "\Outlook" 
$ost = get-ChildItem $OstPath | where { $_.Extension -eq ".ost"}  
$ost | remove-Item -force

Start-Process Outlook


if (Test-Path 'C:\Program Files (x86)\Microsoft Office\office15\lync.exe')
{
    Start-Process 'C:\Program Files (x86)\Microsoft Office\office15\lync.exe'
}
Else
{
   write-host "Lync is not installed"
   if (Test-Path 'C:\Program Files (x86)\Microsoft Office Communicator')
   {
        Start-Process 'C:\Program Files (x86)\Microsoft Office Communicator\communicator.exe'
   }
   Else 
   {
           write-host "Communicator is not installed"
   }
}

2 个答案:

答案 0 :(得分:0)

您可以使用:

$GBL_Username = "Here type your username"
$GBL_Password = ConvertTo-SecureString –String "Here type your password in plain text" –AsPlainText -Force
$GBL_Credential = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $GBL_Username, $GBL_Password

Start-Process 'C:\Program Files (x86)\Microsoft Office\office15\lync.exe' -Credential $GBL_Credential

使用变量$GBL_Credential和第二部分(执行Office Comunicator)

问题:凭证将以纯文本显示,如果有人尝试使用记事本,PowerShell ISE或其他程序编辑脚本,他们可以看到密码。

祝你有个美好的一天。

答案 1 :(得分:0)

从我在剧本中看到的情况来看,没有必要提升。如果这只是为了克服ExecutionPolicy而不是你的方法是错误的。 ExecutionPolicy用于防止用户运行不受信任的脚本。到目前为止,您的脚本就是其中之一。

正确的方法是使用证书对脚本进行签名,并在所有计算机上将ExecutionPolicy设置为Allsigned。然后,用户将只能从现在开始运行已签名的脚本。

如果无法做到这一点,我会看到两个选项:

  1. 用户复制脚本的内容并将其粘贴到powershell窗口
  2. 您将ExecutionPolicy设置为不受限制。请记住,如果用户尝试做一些严肃的事情,他们仍然需要提升,但是对于此脚本,不需要提升。
  3. 总而言之,ExecutionPolicy可以防止你正在尝试做什么,所以不要指望它很容易克服。它也不是你关闭和打开的东西。您应该考虑可接受的内容并将其设置为适合您环境的级别。