我的本地PowerShell脚本如何调用远程PowerShell脚本?

时间:2014-02-17 16:30:11

标签: powershell invoke-command

本地和远程计算机都启用了PSSession。

我认为我的问题是我不知道如何将Invtring-Command转换和传入的字符串转换为ScriptBlock。我可以使用Enter-PSSession通过交互式会话调用所有这些命令。

我的本​​地脚本在脚本块中调用远程脚本。我使用

在本地命令行传递文件名和路径
  

&安培; '。\ CallRemote.ps1'-p“E:\ DeployFolder \ Scripts \” - f“hello.ps1”

本地脚本看起来像这样

Param(
[parameter(Mandatory=$true)]
[alias("p")]
$ScriptPath,
[parameter(Mandatory=$true)]
[alias("f")]
$Scriptfile)
if ($ScriptPath[$ScriptPath.Length - 1] -eq '\')
{
    $ScriptBlock = $ScriptPath + $Scriptfile
}
else
{
    $ScriptBlock = $ScriptPath + '\' + $Scriptfile
}
$appserver = "someurl.com"

$pw = convertto-securestring -AsPlainText -Force -String "password"
$cred = new-object -typename System.Management.Automation.PSCredential -$argumentlist "domain\svc.account",$pw

#initiate remote session for deployment
$session = New-PSSession -ComputerName $appserver -Credential $cred -Name test_remote

#call remote script
Invoke-Command -Session $session -ScriptBlock { $ScriptBlock}
Remove-PSSession -Name test_remote

如果我硬编码路径和文件名前面加上'&'有用。如果没有硬编码,我发现没办法让它工作。

这种特殊的硬编码有效 Invoke-Command -Session $session -ScriptBlock { & "E:\DeployFolder\Scripts\hello.ps1"}

使用Invoke-Command -Session $ session -ScriptBlock {$ ScriptBlock}

,这些尝试更改文件和路径的传入字符串会安静地失败
  1. $ ScriptBlock =“&'”+ $ ScriptPath +'\'+ $ Scriptfile +“`'”
  2. $ ScriptBlock =“& ' " + $ScriptPath + '\' + $Scriptfile + "'”
  3. $ ScriptBlock =“$ ScriptPath +'\'+ $ Scriptfile
  4. 这只是失败了 Invoke-Command -Session $session -ScriptBlock { & $ScriptBlock} 错误消息:

      

    '&'之后的表达在管道元素中产生无效   宾语。它必须导致命令名称,脚本块或CommandInfo   宾语。       + CategoryInfo:InvalidOperation:(:) [],RuntimeException       + FullyQualifiedErrorId:BadExpression

2 个答案:

答案 0 :(得分:0)

您可以使用静态ScriptBlock方法从String创建Create()

$ScriptPath = 'c:\test';
$ScriptFile = 'test.ps1';
$ScriptBlock = [ScriptBlock]::Create("$ScriptPath\$ScriptFile");
...
...

我看到的另一个问题是,您正在使用$ScriptBlock内部的ScriptBlock变量,而该$args变量是您发送到远程计算机的。除非该变量在其他地方定义,否则您无法以这种方式传递参数。您需要使用# This file must exist on the remote filesystem $ScriptFile = 'c:\test\test.ps1'; # Invoke the script file on the remote system Invoke-Command -Session $Session -ScriptBlock { & $args[0]; } -ArgumentList $ScriptFile; 自动变量。

{{1}}

答案 1 :(得分:0)

请使用:

$cmd = "c:\Programs (x86)\...\command.exe"
Invoke-Command -Session $session -ScriptBlock { & $using:cmd}

有关更多信息,请参阅http://www.padisetty.com/2014/05/all-about-powershell-scriptblock.html