我使用C#将以下脚本添加到PowerShell实例。我想自动执行此操作,以便如何将-Credential参数替换为我创建的PSCredential对象?另外,我可以为LocalCredential使用不同的PSCredential对象吗?我知道如何创建PSCredential对象。我只是不知道如何将它插入到我的ps.AddScript方法中。
Add-Computer -ComputerName '"+ strMachineName + @"' -LocalCredential '.\Administrator' -DomainName 'MyDomain' -Credential MyDomain\MyUserName -Restart -Force");
我的确切代码:
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ComputerName = strMachineName;
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
PowerShell ps = PowerShell.Create()
ps.AddScript(@"Add-Computer -ComputerName '"+ strMachineName + @"' -LocalCredential '.\Administrator' -DomainName 'MyDomain' -Credential MyDomain\Username -Restart -Force");
ps.Runspace = runspace;
ps.Invoke();
我根据Mathias R. Jessen的建议改变了我的代码。我的目标是在同一个局域网上添加一台新机器。我尝试从Invoke方法捕获ObjectModelCollection集合,看看我是否可以通过返回的集合学习任何东西。 调用invoke方法并且远程计算机不重新启动后,集合计数为0。请参阅我修改后的代码。
修订后的代码
using (PowerShell ps = PowerShell.Create())
{
//secureString for a Domain user on the domain that I want to
join the remote PC to
System.Security.SecureString secureString1 = new
NetworkCredential("DomainAdminUserName", DomainPassword").SecurePassword;
//secureString for a loca Administrator on the remote machine
System.Security.SecureString secureString2 = new NetworkCredential("Administrator", "AdminPassword").SecurePassword;
ps.Runspace = runspace;
PSCredential localCred = new PSCredential("Administrator", secureString2);
PSCredential domainCred = new PSCredential("DomainAdminUserName", secureString1); //UNDONE Should not be Greer
ps.AddCommand("Add-Computer")
.AddParameter("ComputerName", strMachineName)
.AddParameter("LocalCredential", localCred)
.AddParameter("DomainName", "MyDomain")
.AddParameter("Credential", domainCred)
.AddParameter("Restart")
.AddParameter("Force");
try
{
//INVOKE
System.Collections.ObjectModel.Collection<PSObject> coll = ps.Invoke();
blnSuccess = true;
}
catch
{
blnSuccess = false;
}
finally
{
runspace.Close();
}
return blnSuccess;
更新
现在一切正常。我被远程PC上的防火墙阻挡了。我知道在远程计算机上禁用防火墙的唯一方法是使用Sysinternals中的PSEXEC,如下所示:
Process p = new Process();
p.StartInfo.FileName = @"C:\PsExec.exe";
p.StartInfo.UseShellExecute = true;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.Arguments = @"\\<REMOTEPCNAME> -u Administrator -p <PASSWORD> netsh firewall set opmode disable";
p.Start();
p.WaitForExit();
如果有一种方法可以在不使用PSEXEC的情况下在Powershell中实现这一点,我很乐意听到它。
答案 0 :(得分:1)
您应该使用AddCommand()和AddParameter()方法而不是AddScript()。
然后,您可以在代码中创建PSCredential对象并将其传递给AddParameter()。
答案 1 :(得分:1)
使用AddCommand()
后跟AddParameter()
代替AddScript()
:
PSCredential localCred = ...;
PSCredential domainCred = ...;
ps.AddCommand("Add-Computer")
.AddParameter("ComputerName", strMachineName)
.AddParameter("LocalCredential", localCred)
.AddParameter("DomainName", "MyDomain")
.AddParameter("Credential", domainCred)
.AddParameter("Restart")
.AddParameter("Force");