我一直在试图弄清楚如何启用Runspace Powershell命令作为另一个用户运行,我找到了像this这样的例子:
var con = new WSManConnectionInfo();
con.Credential = new PSCredential("user", "pass".ToSecureString());
Runspace runspace = RunspaceFactory.CreateRunspace(con);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add("dir");
pipeline.Commands.Add("Out-String");
var results = pipeline.Invoke();
runspace.Close();
但是这不起作用,因为con.Credential
是一个只读属性。我不知道这个人怎么能宣称它有效。
当我尝试不同的方式时:
var cred = new PSCredential(objWINS + "\\" + objUser, objPW.ToSecureString());
var con = new WSManConnectionInfo(cred);
WSManConnectionInfo
类需要更多信息,例如Uri和Shell字符串。我只是想在这里运行Powershell命令,我没有需要连接的Uri,我也不知道shell是什么,我在搜索中唯一能找到的就是这个URL:
“Qazxswpoi”
这个课程里没有很多信息,我真的无法收集任何关于Uri至少添加内容的信息。
这是您为http://schemas.microsoft.com/powershell/Microsoft.PowerShell对象指定凭据的方式:
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;
}
(使用answer方法)