首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Get-Credentials - Odd结果调用另一个powershell脚本

使用Get-Credentials - Odd结果调用另一个powershell脚本
EN

Stack Overflow用户
提问于 2018-10-23 21:22:24
回答 1查看 488关注 0票数 0

编辑:

我有一个powershell脚本,它以提升的域管理员身份调用另一个脚本,该脚本返回一个访问被拒绝的错误,如下所示:

代码语言:javascript
复制
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

使用此方法调用脚本会产生错误:

代码语言:javascript
复制
$Cred = Get-Credential

Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -File $ScriptLocation" -Credential $Cred

但是,如果我只需右键单击并以管理员身份运行,然后输入我的域凭据来调用脚本(不使用$Cred),就可以正常工作:

代码语言:javascript
复制
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -File $ScriptLocation"

我调用的脚本如下所示:

代码语言:javascript
复制
$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中存储我的域管理员凭据并将其传递给脚本会导致访问被拒绝

EN

回答 1

Stack Overflow用户

发布于 2018-10-23 21:50:35

根据TheIncorrigible1的注释,您可以在脚本的开头添加以下内容,以检查它是否以管理员身份运行。如果不是,它将以admin身份重新启动

代码语言:javascript
复制
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设置,可能会提示您允许它以提升的权限运行。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52950225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档