powershell 此代码块将允许您以其他用户身份运行后续cmdlet

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 此代码块将允许您以其他用户身份运行后续cmdlet相关的知识,希望对你有一定的参考价值。

function Get-ImpersonatetLib {
	if ($script:ImpersonateLib) {
		return $script:ImpersonateLib
	}
	
	$sig = @'
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("kernel32.dll")]
public static extern Boolean CloseHandle(IntPtr hObject);
'@
	$script:ImpersonateLib = Add-Type -PassThru -Namespace 'Lib.Impersonation' -Name ImpersonationLib -MemberDefinition $sig
	
	return $script:ImpersonateLib
	
}

function ImpersonateAs([PSCredential]$cred) {
	[IntPtr]$userToken = [Security.Principal.WindowsIdentity]::GetCurrent().Token
	$userToken
	$ImpersonateLib = Get-ImpersonatetLib
	
	$bLogin = $ImpersonateLib::LogonUser($cred.GetNetworkCredential().UserName, $cred.GetNetworkCredential().Domain, $cred.GetNetworkCredential().Password,
		9, 0, [ref]$userToken)
	
	if ($bLogin) {
		$Identity = New-Object Security.Principal.WindowsIdentity $userToken
		$context = $Identity.Impersonate()
	}
	else {
		throw "Can't Logon as User $cred.GetNetworkCredential().UserName."
	}
	$context, $userToken
}

function CloseUserToken([IntPtr]$token) {
	$ImpersonateLib = Get-ImpersonatetLib
	
	$bLogin = $ImpersonateLib::CloseHandle($token)
	if (!$bLogin) {
		throw "Can't close token"
	}
}

$PASSWORD = 'password'
$user = "domain\user"
$secureString = ConvertTo-SecureString -AsPlainText -Force -String $PASSWORD
$credential = New-Object `
						 -TypeName System.Management.Automation.PSCredential `
						 -ArgumentList $user, $secureString
						
($oldToken, $context, $newToken) = ImpersonateAs -cred $Credential

#commands from this point forward will be run as the credential you provided
#Get-Service <--- now runs as the context user

以上是关于powershell 此代码块将允许您以其他用户身份运行后续cmdlet的主要内容,如果未能解决你的问题,请参考以下文章

markdown 这是`jupyter_client`的一个简单包装器,它允许您以编程方式创建Jupyter内核,在其中执行代码,以及retri

您的电子邮件客户端是不是允许您以编程方式添加自定义标头?

php 允许您以编程方式(动态)将菜单项添加到WordPress菜单。

powershell 此脚本允许您将Java Cryptography Extension(JCE)无限强度管辖区域策略文件“安装”到嵌入式JRE中

powershell PowerShell:启动PowerShell作为其他用户提升

powershell 这为SharePoint 2013发布站点对象缓存设置了Portal Supper用户和阅读器。它允许指定用户(用户/读者)到