【问题标题】:Elevating PowerShell script permissions提升 PowerShell 脚本权限
【发布时间】:2021-06-22 01:26:00
【问题描述】:

我正在尝试运行脚本来管理一些 VHD 磁盘,但由于需要提升权限,磁盘装载失败。运行脚本的用户是本地管理员,但我认为 UAC 阻止了它。返回的错误是:“DiskState=Failed to mount disk - “Access to a CIM resource was not available to the client”

理想情况下,我需要脚本在提升的命令提示符下自动运行。有什么想法可以通过编程方式实现吗?

我正在运行的脚本是这样的:

$location = "C:\temp"
$name = "downloadfile"
$Author = "FSLogix"
$FilePath = "Filepath here"
$LogFilePath = "Logfilepath here"

# Force to create a zip file 
$ZipFile = "$location\$Name.zip"
New-Item $ZipFile -ItemType File -Force

$RepositoryZipUrl = "https://github.com/FSLogix/Invoke-FslShrinkDisk/archive/master.zip"

# download the zip 
Write-Host 'Starting downloading the GitHub Repository'
Invoke-RestMethod -Uri $RepositoryZipUrl -OutFile $ZipFile
Write-Host 'Download finished'

#Extract Zip File
Write-Host 'Starting unzipping the GitHub Repository locally'
Expand-Archive -Path $ZipFile -DestinationPath $location -Force
Write-Host 'Unzip finished'
 
# remove the zip file
Remove-Item -Path $ZipFile -Force

# Run the FSLogix Optimisation
C:\temp\Invoke-FslShrinkDisk-master\Invoke-FslShrinkDisk.ps1 -Path $FilePath -Recurse -PassThru -LogFilePath $LogFilePath\logfile.csv

【问题讨论】:

  • 您有两个选项,如果不存在提升的权限则不运行,或者如果不存在权限则提示 UAC 提升。你要哪一个?
  • 脚本需要通过自动化任务运行,因此无法提示输入 UAC。附近有什么办法吗?一定有办法的。
  • 不。简单的回答:在运行时,如果没有管理员权限,您就不能使用管理员权限,如果可能的话,那将是非常糟糕的。如果您要自动执行此操作,您是如何运行脚本的?
  • 运行脚本的用户确实拥有本地管理员权限,但默认情况下,Powershell 脚本不会在提升的权限下运行。它是通过一个名为 Nerdio 的脚本操作来运行的。
  • hmmm 我不认为默认情况下以管理员身份运行 powershell 但您可能需要查看 nerdio 的文档以查看是否有以管理员权限运行的选项

标签: powershell powershell-remoting


【解决方案1】:

您可以使用 Powershell 作为单独的进程来提升 PS 脚本,并使其“以管理员身份运行”,如下所示:

start-process PowerShell -verb runas

Powershell -Command "Start-Process PowerShell -Verb RunAs"

除此之外,您还可以调节它。 PGK 共享了一个漂亮的条件代码,它也可以提供帮助:

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
}

【讨论】:

  • 不应该是exit 而不是Break 来关闭未提升的会话吗?
  • 是的。退出会做@Theo
猜你喜欢
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
相关资源
最近更新 更多