我尝试使用PowerShell创建用户。在本地计算机上运行良好。但是如何使用远程PowerShell在远程计算机上创建本地用户帐户?
脚本localwindows.ps1内容如下:
$comp = [adsi]'WinNT://machinename,computer';
$user = $comp.Create('User', 'account4');
$user.SetPassword('change,password.10');
$user.SetInfo();
我尝试通过C#做同样的事情:
PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machinename", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
String file = "C:\\localwindows.ps1";
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(System.IO.File.ReadAllText(file));
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = pipeline.Invoke();
}
这在本地运行时是可以正常工作的。但是在远程计算机上,它会抛出“创建:拒绝访问”的异常。