使用Ruby的Windows命令行脚本。 #each循环意外行为

时间:2017-04-18 17:49:28

标签: ruby windows

我期待多台机器关闭进程并重新启动.bat文件(我正在编写Windows脚本。)它只适用于第一台机器。

nodes = (1234..1235).to_a
nodes.map! { |node| "pc" + node.to_s }
apps_to_close = ["iexplore.exe", "powershell.exe", "ruby.exe", "chrome.exe", 
  "cmd.exe", "taskhost.exe", "git.exe", "git-tfs.exe"]

def process_node(apps_to_close, node)
  begin
     apps_to_close.each do |app|
      `taskkill.exe /S #{node} /U joe_user /P joe_pass /IM #{app} /F`
    end
     `@powershell cmdkey.exe /add:#{node} /user:joe_user /pass:joe_pass; 
      schtasks /RUN /TN "start_my_sched_task" /s "#{node}"`
  rescue
    puts "#{node} could not be restarted"
  end
end

nodes.each do |node|
  process_node(apps_to_close, node)
end

1 个答案:

答案 0 :(得分:0)

修正了它:

nodes = (1234..1235).to_a
nodes.map! { |node| "pc" + node.to_s }
apps_to_close = ["iexplore.exe", "powershell.exe", "ruby.exe", "chrome.exe", 
  "cmd.exe", "taskhost.exe", "git.exe", "git-tfs.exe"]

def process_node(apps_to_close, node)
  begin
     apps_to_close.each do |app|
      `taskkill.exe /S #{node} /U joe_user /P joe_pass /IM #{app} /F`
    end
     Process.spawn("@powershell cmdkey.exe /add:#{node} /user:joe_user /pass:joe_pass; 
      schtasks /RUN /TN \"start_my_sched_task\" /s \"#{node}\"")
  rescue
    puts "#{node} could not be restarted"
  end
end

nodes.each do |node|
  process_node(apps_to_close, node)
end