编辑:
我有一个powershell脚本,它以提升的域管理员身份调用另一个脚本,该脚本返回一个访问被拒绝的错误,如下所示:
Exception calling "Add" with "1" argument(s): "Access is denied.
"
At \\server\software$\!SystemSetup\PS_Scripts\LocalAdmin.ps1:16 char:5
+ $AdminGroup.Add($User.Path)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
使用此方法调用脚本会产生错误:
$Cred = Get-Credential
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -File $ScriptLocation" -Credential $Cred
但是,如果我只需右键单击并以管理员身份运行,然后输入我的域凭据来调用脚本(不使用$Cred
),就可以正常工作:
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -File $ScriptLocation"
我调用的脚本如下所示:
$WindowsVersion = Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption
If ($WindowsVersion -match 'Microsoft Windows 10 Enterprise') {
$DomainName = "DOMAIN.COM"
$ComputerName = (hostname)
$Username = (Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -ExpandProperty UserName).Split('\')[1]
$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"
$User = [ADSI]"WinNT://$DomainName/$UserName,user"
$AdminGroup.Add($User.Path)
Write-Host "$Username added to Administrators"
} Elseif ($WindowsVersion -match 'Microsoft Windows 7 Enterprise' -or $WindowsVersion -match 'Microsoft Windows 7 Professional') {
$DomainName = "DOMAIN.COM"
$ComputerName = (hostname)
$Username = (Get-WmiObject -Class Win32_ComputerSystem | Select-Object -ExpandProperty UserName).Split('\')[1]
$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"
$User = [ADSI]"WinNT://$DomainName/$UserName,user"
$AdminGroup.Add($User.Path)
Write-Host "$Username added to Administrators"
} Else {
Write-Host "Could not determine OS version"
}
我不明白为什么一旦访问到$AdminGroup.Add($User.Path)
,在$Cred中存储我的域管理员凭据并将其传递给脚本会导致访问被拒绝
发布于 2018-10-23 13:50:35
根据TheIncorrigible1的注释,您可以在脚本的开头添加以下内容,以检查它是否以管理员身份运行。如果不是,它将以admin身份重新启动
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
}
然后,根据您的UAC设置,可能会提示您允许它以提升的权限运行。
https://stackoverflow.com/questions/52950225
复制