我找到了一些解决方法。在远程会话中模拟管理员凭据
function EntryPoint()
{
ImportModule-Impersonate;
$impersonate = new-object UserSession.Impersonate;
try
{
if ($impersonate.Login("SKODA", "Administrator", "*****") -eq $false) {
throw new Exception("Invalid credentials");
}
Import-Module NetworkLoadBalancingClusters
Get-NlbClusterNode;
}
finally
{
$impersonate.Dispose();
}
};
function ImportModule-Impersonate {
$assem = @();
$source = @"
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
namespace UserSession
{
public class Impersonate : IDisposable
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
private WindowsImpersonationContext _impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
public bool Login(String domain, String userName, String password)
{
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
_impersonationContext = tempWindowsIdentity.Impersonate();
if (_impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
return false;
}
public void Logout()
{
if (_impersonationContext != null)
{
_impersonationContext.Undo();
_impersonationContext = null;
}
}
public void Dispose()
{
Logout();
}
}
}
"@;
Add-Type -ReferencedAssemblies $assem -TypeDefinition $source -Language CSharp
}
EntryPoint;