如何让脚本检查管理员权限,如果没有,如何以管理员身份重新运行
How to have a script check for admin privileges', and rerun itself as admin if it doesn't
所以我正在尝试为我在 powershell 中遇到的问题创建一个解决方案。
我需要想出一种方法来检查我的脚本是否 运行 具有管理权限。如果不是,则需要使用管理员权限重新运行。
我的情况很特别,因为我们的普通用户帐户没有权限,所以我需要输入其他凭据。
如果这有帮助,我们的管理帐户在名称中确实有一个结束标识符,如果我们可以过滤掉它的话。前任。 “John.Doe.A”和 .A 表示这是一个管理员帐户。
继续我的评论。
您的情况并非独一无二。它在这里和许多其他地方被问了很多。
'powershell SecretManagement module' auto elevate
Sample hit:
您将需要的凭据存储在 'Windows Credential Manager' 中,并根据需要从中调用。 MS 甚至为这种用例提供了一个新的 Secrets Module。通过 MS Docs 查看有关该主题的更多详细信息。
像这样:
SecretManagement and SecretStore are Generally Available
https://devblogs.microsoft.com/powershell/secretmanagement-and-secretstore-are-generally-available
还有这个:
Microsoft.PowerShell.SecretManagement
Get-Secret
Get-SecretInfo
Get-SecretVault
Register-SecretVault
Remove-Secret
Set-Secret
Set-SecretInfo
Set-SecretVaultDefault
Test-SecretVault
Unregister-SecretVault
使用这个。
$adminrole = ([Security.Principal.WindowsBuiltInRole] "Administrator")
$wid = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent())
If (-not $wid.IsInRole($adminrole)) {
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"
$newProcess.Arguments = $myInvocation.MyCommand.Definition
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
exit
}
所以我正在尝试为我在 powershell 中遇到的问题创建一个解决方案。
我需要想出一种方法来检查我的脚本是否 运行 具有管理权限。如果不是,则需要使用管理员权限重新运行。
我的情况很特别,因为我们的普通用户帐户没有权限,所以我需要输入其他凭据。
如果这有帮助,我们的管理帐户在名称中确实有一个结束标识符,如果我们可以过滤掉它的话。前任。 “John.Doe.A”和 .A 表示这是一个管理员帐户。
继续我的评论。
您的情况并非独一无二。它在这里和许多其他地方被问了很多。
'powershell SecretManagement module' auto elevate
Sample hit:
您将需要的凭据存储在 'Windows Credential Manager' 中,并根据需要从中调用。 MS 甚至为这种用例提供了一个新的 Secrets Module。通过 MS Docs 查看有关该主题的更多详细信息。
像这样:
SecretManagement and SecretStore are Generally Available
https://devblogs.microsoft.com/powershell/secretmanagement-and-secretstore-are-generally-available
还有这个:
Microsoft.PowerShell.SecretManagement
Get-Secret
Get-SecretInfo
Get-SecretVault
Register-SecretVault
Remove-Secret
Set-Secret
Set-SecretInfo
Set-SecretVaultDefault
Test-SecretVault
Unregister-SecretVault
使用这个。
$adminrole = ([Security.Principal.WindowsBuiltInRole] "Administrator")
$wid = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent())
If (-not $wid.IsInRole($adminrole)) {
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"
$newProcess.Arguments = $myInvocation.MyCommand.Definition
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
exit
}