1

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

我认为我的问题是我不知道如何将传入的字符串转换为 ScriptBlock 以供 Invoke-Command 使用。我可以使用 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

这只是失败 Invoke-Command -Session $session -ScriptBlock { & $ScriptBlock} 并显示错误消息:

管道元素中“&”之后的表达式产生了无效对象。它必须产生一个命令名称、脚本块或 CommandInfo 对象。+ CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : BadExpression

4

2 回答 2

0

您可以使用静态方法ScriptBlock从 a创建一个。StringCreate()

$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;
于 2014-02-17T16:57:14.140 回答
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

于 2015-05-06T12:36:21.063 回答