我尝试远程访问服务器,运行驻留在该服务器上的脚本并捕获显示的信息。存储在本地文件中

时间:2014-06-04 02:53:23

标签: powershell psexec start-job

##this code starts job but never exits or get any output###
clear

$test = 1

$Username = Read-host "Username (Example:Hosting.com\Your Username)"

""

$Pass = Read-Host -assecurestring "Password"


$Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))


$Servers = Get-Content "c:\temp\new\Servers.txt" 

foreach ($Server in $Servers)

{

  $files= "c:\temp\new\new.ps1"

  foreach ($file in $files)

  {

   xcopy $file \\$Server\C$ /Y

  }

}

$CSVContent=@()

$sb = {c:\temp\new\PsExec.exe -h "\\$Server" /accepteula -u $Username -p $password -d cmd.exe /c "echo . | Powershell.exe -executionpolicy bypass -file c:\new.ps1 " > "$Test.txt"}


foreach ($Server in $Servers) 

{

start-job -scriptblock $sb -ArgumentList $server

$test++

}

get-job | wait-job | receive-job

1 个答案:

答案 0 :(得分:0)

以下是我刚刚编写的内容,可以执行您想要的操作,并将所有输出打印到本地PC上的文件(运行脚本的位置)

$execDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$Servers = Get-Content "c:\temp\servers.txt"

foreach ($Server in $Servers)

{
    #echo $Server
copy-item "C:\temp\new\new.ps1" \\$server\c$\temp\
& "$execdir\psexec.exe" \\$server powershell.exe -noprofile -executionpolicy Bypass "C:\data\new.ps1" >> "C:\temp\logs.txt"

}

如果脚本说它无法运行powershell.exe,只需添加exe所在位置的完整路径 我不确定你是否能够使用这些工作,除非你使用的是PowerShell v4并使用foreach -Parallel cmdlett

http://technet.microsoft.com/en-us/library/jj713711.aspx