如何结合两个foreach循环?

我已经看过如何将多个命令与psexec结合起来,但没有任何方法似乎工作。 也许这是因为我在PowerShell中运行脚本而不是cmd.exe?

我需要创build用户帐户并将其添加到非域计算机上的本地pipe理员组(Windows 2003)。 我得到了以下脚本(工作),但我想知道是否有一个简单的方法来组合两个foreach循环,因为它必须build立每个服务器两次psexec连接。

$username = Read-Host "User name:" $password = Read-Host "Password:" $fullname = Read-Host "Full name:" $computers = Get-Content C:\Tools\scripts\ServerList.txt foreach ($computer in $computers) { psexec \\$computer -u username -p password net user $username $password /add /fullname:""$fullname"" /comment:"Comment" } foreach ($computer in $computers) { psexec \\$computer -u username -p password net localgroup Administrators $username /add } 

正如我所提到的,这是在PowerShell中运行。 我正在运行的服务器是没有安装PowerShell的Workgroup Windows 2003 Server。

正如@CIA所说,你可以通过在一个循环中运行两次psexec来组合循环。

 $username = Read-Host "User name:" $password = Read-Host "Password:" $fullname = Read-Host "Full name:" $computers = Get-Content C:\Tools\scripts\ServerList.txt foreach ($computer in $computers) { psexec \\$computer -u username -p password net user $username $password /add /fullname:""$fullname"" /comment:"Comment" psexec \\$computer -u username -p password net localgroup Administrators } 

但是,似乎你真正要问的是如何在一个psexec会话中同时运行两个net命令

 $username = Read-Host "User name:" $password = Read-Host "Password:" $fullname = Read-Host "Full name:" $computers = Get-Content C:\Tools\scripts\ServerList.txt foreach ($computer in $computers) { psexec \\$computer -u username -p password net user $username $password ullname"" /comment:"Comment" ^&^& net localgroup Administrators } 

你可以这样试试,但是我不确定它会起作用。 &&使用^转义,以便它被传递给psexec而不是在本地解释,然后在本地运行第二个net命令。

替代

你可以做什么,而不是使用psexec ,并使用PowerShell远程处理。 只需要在每台想要远程访问的机器上启用。 我意识到这可能是一个承诺,但它是值得的,因为它更多样化,基本上,这是未来。

如果您在域中,甚至可以使用组策略来启用PowerShell远程处理 (完全公开:这是我的文章)。

如果你这样做,你的代码将如下所示:

 $username = Read-Host "User name:" $password = Read-Host "Password:" $fullname = Read-Host "Full name:" $computers = Get-Content C:\Tools\scripts\ServerList.txt foreach ($computer in $computers) { Invoke-Command -ComputerName $computer -ArgumentList $username,$password,$fullname -ScriptBlock { param($u,$p,$f) # Everything in here is executed on the remote computer net user $u $p /add /fullname:""$f"" /comment:"Comment" net localgroup Administrators } }