2014-09-10 40 views
0

PowerShell脚本返回代码是否需要调用命令

  1. 启用PSRemoting在远程计算机上
  2. 执行SETUP.EXE在远程计算机上
  3. 禁用PSRemoting在远程计算机上

如何确保在远程计算机能够执行setup.exe后禁用PSRemoting?

我是否在远程计算机能够执行setup.exe之前禁用PSRemoting?

$password = get-content D:\Script\cred.txt | convertto-securestring 
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "Administrator",$password 
$j = "remote_computer" 

$comp = "\\"+$j 

$exe = "setup.exe" 
[String]$cmd = "cmd /c 'C:\share\$exe'" 
[ScriptBlock]$sb = [ScriptBlock]::Create($cmd) 


$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) 
$str = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) 
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) 



$enable_command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $str -accepteula powershell.exe c:\share\ps_enable.ps1" 

Invoke-Expression $enable_command 


try{ 
    invoke-command -ComputerName $j -Credential $credentials -ScriptBlock $sb 

} 
catch [System.Exception]{ 
    continue 
} 


$disable_command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $str -accepteula powershell.exe c:\share\ps_disable.ps1" 

Invoke-Expression $disable_command 

回答

1

很简单,使用AsJob开关进行Invoke-Command并将其分配给一个变量。然后使用Wait-Job,以便在继续禁用PSRemoting之前知道已完成的工作。

try{ 
    $SetupJob = invoke-command -ComputerName $j -Credential $credentials -ScriptBlock $sb -AsJob 

} 
catch [System.Exception]{ 
    continue 
} 

$SetupJob|Wait-Job 

$disable_command = "D:\PSTools\PsExec.exe $comp -u Administrator -p $str -accepteula powershell.exe c:\share\ps_disable.ps1" 

Invoke-Expression $disable_command 
相关问题