【问题标题】:Forwarding output of Invoke-Command on Remote Server在远程服务器上转发 Invoke-Command 的输出
【发布时间】:2018-01-08 20:55:26
【问题描述】:

要删除我们服务器上的旧文件,我们使用 PowerShell 和 Invoke-Command 在服务器上运行远程命令:

Invoke-Command {
    Param($ServerPath)
    Remove-Item -Path $ServerPath -Recurse -Force -Verbose
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
# The parsed credentials are from a different user than the one who opened the
# shell

命令本身按需要工作。但这只是将删除的文件写入控制台,而不是我想将其转发到变量/文件(最好存储在执行命令的客户端上)。

我尝试了以下选项但没有成功:

Invoke-Command {
    Param($ServerPath)
    Remove-Item -Path $ServerPath -Recurse -Force -Verbose 4>>"%ScriptPath%\log.txt"
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
Invoke-Command {
    Param($ServerPath)
    Remove-Item -Path $ServerPath -Recurse -Force -Verbose >>"%ScriptPath%\log.txt"
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
Invoke-Command {
    Param($ServerPath)
    Remove-Item -Path $ServerPath -Recurse -Force -Verbose
} 4>>"%ScriptPath%\log.txt" -Computer servername -Credential $Credential -ArgumentList $ServerPath
$log = Invoke-Command {
    Param($ServerPath)
    Remove-Item -Path $ServerPath -Recurse -Force -Verbose
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
$log = Invoke-Command {
    Param($ServerPath)
    return (Remove-Item -Path $ServerPath -Recurse -Force -Verbose)
} -Computer servername -Credential $Credential -ArgumentList $ServerPath

一种解决方法可能是启动与服务器的远程会话并在那里执行,但我不想只为一个命令启动和取消远程会话。

有谁知道我在转发时做错了什么?

【问题讨论】:

  • 尝试在客户端重定向详细输出,或在Remove-Item 命令上使用-PassThru 仅返回对象本身并在客户端解析它们以获得您需要/想要的内容。
  • 使用Tee-Object 将信息记录到远程服务器上的文件中,并将其传递回调用命令的本地主机?

标签: powershell logging remote-access invoke-command


【解决方案1】:

我最初的猜测是您的第 3 个变体应该有效:

Invoke-Command {
    Param($ServerPath)
    Remove-Item -Path $ServerPath -Recurse -Force -Verbose
} 4>>"%ScriptPath%\log.txt" -Computer servername ...

但是,不幸的是,重定向冗长的output stream 似乎不适用于远程连接。要获得您想要的结果,您需要将详细输出流合并到脚本块内的成功输出流中,然后将成功输出流重定向到脚本块外:

Invoke-Command {
    Param($ServerPath)
    Remove-Item -Path $ServerPath -Recurse -Force -Verbose 4>&1
} >>"%ScriptPath%\log.txt" -Computer servername ...

关于您的其他方法:

  • #1 不起作用,因为重定向会在 remote 主机上创建文件。
  • #2 不起作用,因为>> 重定向成功输出流,而不是详细输出流,它仍然在远程主机上创建文件。
  • #4 不起作用,因为 $variable = ... 将成功输出流上的输出分配给变量,而不是详细流上的输出。
  • #5 不工作的原因与 #4 相同。 return 关键字只影响控制流,而不影响函数返回的输出(显然,return 语句之后创建的输出除外)。

【讨论】:

  • 嘿@Ansgar,感谢您的回答,但遗憾的是,上述方法对我不起作用。输出会打印到 shell,但不会打印到日志文件。我得到的结果与我不指定输出流时的结果相同。
  • @Paxz 我对此表示怀疑。请提供证据。另外,您正在运行哪些 PowerShell 版本(本地和远程)?
  • 我检查了服务器,似乎两者都在运行 PS 2.0,而客户端运行的是 PS 5.0。我们在周二开放了维护 Windows,届时将包括 PS 升级。升级后我会再试一次,如果仍然失败,我会提供输出和更好的场景描述。
  • 重定向 4>&1 在 PowerShell v2 中不可用。除非您至少可以升级到 v3,否则您就不走运了。
  • 升级到 PS 3.0 后,它的工作原理与您描述的一样。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多