0

我想这已经被问过很多次了,但我找不到适合我的答案。

  • 我需要从变量构造一个命令行。
  • 我需要运行该命令行可执行文件。
  • 我需要将结果显示在与我的脚本相同的屏幕上。

我正在尝试使用自定义源和目标运行 Putty SCP。

我已经搞砸了&Invoke-Expression但这是不可能的。PowerShell 中的一些简单的#1 用例非常难,它们会吃掉它的所有好处。

我能看到的唯一方法是在新的 Process 实例中运行它并设置所有输出重定向,然后在完成后将其通过管道传回 PS 屏幕。

而且我知道这可能会失败,因为输出缓冲区可能会变满,除非您被事件所吸引并将其挖出。

另一种方法是将我的命令行写入批处理文件并运行它。

任何帮助表示赞赏。必须有一个更简单的方法。

编辑

例如:

[string]$scpPath = Find-PathToPuttyScpExecutable;
[string]$scpArguments = "-v -r -pw " + $MarkLogicServerPassword + " " + $MarkLogicSourcePath + " " + $MarkLogicServerUserName + "@" + $ServerName + ":" + $MarkLogicDestinationRootPath

我需要执行$scpPath + " " + $scpArguments.

4

1 回答 1

4

不要太执着于弦乐。只需运行带参数的命令:

[string]$scpPath = Find-PathToPuttyScpExecutable;
&$scpPath -v -r -pw $MarkLogicServerPassword $MarkLogicSourcePath "$($MarkLogicServerUserName)@$($ServerName):$($MarkLogicDestinationRootPath)"

PowerShell 将为您处理报价。在大多数情况下,它运作良好,我怀疑你会在这里偶然发现边缘情况。

如果您必须即时创建参数列表,那么您应该使用一个数组并传递它:

$scpArguments = '-v',
                '-r',
                '-pw',
                $MarkLogicServerPassword,
                $MarkLogicSourcePath,
                "$($MarkLogicServerUserName)@$($ServerName):$($MarkLogicDestinationRootPath)"

&$scpPath @scpArguments
于 2013-03-20T13:32:27.010 回答