IMO 最简单的方法是使用有效凭据连接到目标计算机,然后您可以在没有任何凭据提示的情况下执行任何代码,为此,您需要创建一个PSCredential
对象,它是一个用户名和一个安全字符串密码。
要将纯文本转换为 SecureString,您可以使用以下方法:
private SecureString GetSecurePassword(string password)
{
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
return securePassword;
}
然后你的下一步是创建一个WSManConnectionInfo
目标计算机的对象,并添加凭据,您可以再次使用此方法:
WSManConnectionInfo GetConnectionInfo(string computerName)
{
PSCredential creds = new PSCredential("UserName",
GetSecurePassword("Password"));
Uri remoteComputerUri = new Uri(string.Format("http://{0}:5985/wsman", computerName));
WSManConnectionInfo connection = new WSManConnectionInfo(remoteComputerUri,
"http://schemas.microsoft.com/powershell/Microsoft.PowerShell",
creds);
return connection;
}
最后,连接到目标计算机并创建一个 Runspace:
WSManConnectionInfo connectionInfo = GetConnectionInfo("computerName");
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
回到你的代码:
Pipeline pipeline = runspace.CreatePipeline();
[...]