我想在多个服务器(近40-50服务器)上运行此局部(近40-50服务器)

$ username=“用户”

$Password = "Password"

$servers = get-content "c:\temp\servers.txt"

$sb = {c:\temp\PsExec.exe -h \\$server -u $Username -p $password cmd.exe /c "echo . | Powershell.exe -executionpolicy bypass -file c:\script.ps1" > "$env:userprofile\Desktop\output.txt"} 

foreach($server in $servers)
{
    start-job -ScriptBlock $sb
}
.

如果我删除启动作业,则此代码正常工作,但是在另一个之后执行一个,这需要大量时间。

我不能使用pssession或调用命令,因为它受到环境中的限制。

此代码永远不会退出。它停止在这个位置:

 + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PsExec v1.98 - Execute processes remotely
Copyright (C) 2001-2010 Mark Russinovich
Sysinternals - www.sysinternals.com
.

有帮助吗?

解决方案

首先,您不会将任何变量传递到作业中。您需要的是在ScriptBlock中使用$ args变量,然后通过-argumentList传递您想要的变量。

$Password = "Password"

$servers = get-content "c:\temp\servers.txt"

$sb = {
  c:\temp\PsExec.exe -h \\$args[0] -u $args[1] -p $args[2] cmd.exe /c "echo . | Powershell.exe -executionpolicy bypass -file c:\script.ps1" > "$args[3]\Desktop\output.txt"
} 

foreach($server in $servers)
{
    start-job -ScriptBlock $sb -ArgumentList $server,$Username,$password,$env:userprofile
}
.

我可能不需要通过环境变量,但它似乎是你对变量有一个范围问题。

或者,您可以在ScriptBlock中使用Param块来命名变量,它基本上将传递到命名变量的参数定位地映射到命名变量。

$Password = "Password"

$servers = get-content "c:\temp\servers.txt"

$sb = {
  Param ($Server,$UserName,$Password,$UserProfile)

  c:\temp\PsExec.exe -h \\$Server -u $UserName -p $Password cmd.exe /c "echo . | Powershell.exe -executionpolicy bypass -file c:\script.ps1" > "$UserProfile\Desktop\output.txt"
} 

foreach($server in $servers)
{
    start-job -ScriptBlock $sb -ArgumentList $server,$Username,$password,$env:userprofile
}
.

我希望这有帮助。 干杯,克里斯。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top