gpt4 book ai didi

powershell - 使用 Tee 从另一个 shell 运行 PowerShell

转载 作者:行者123 更新时间:2023-12-03 20:00:26 30 4
gpt4 key购买 nike

我想学习从另一种 shell 或语言执行 PowerShell 命令,例如 python os.system() .我想要实现的是以下内容:

  • 执行 PowerShell 命令
  • 输出到控制台和文件
  • 返回命令退出代码

  • 我认为这给出了我想要实现的想法,假设使用 cmd.exe 作为调用者环境:
    powershell -NoProfile -command "& { cat foo.txt  | Tee-Object ps-log.txt; exit $LASTEXITCODE }"
    echo %errorlevel%
    这里有一些问题。首先,我不能在命令中使用引号,例如:
    powershell -NoProfile -command "& { cat `"foo bar.txt`"  | Tee-Object ps-log.txt; exit $LASTEXITCODE }"
    cat参数似乎是不加引号传递的,所以 cat查找“bar.txt”参数。
    我想 $LASTEXITCODE很快就扩展了,也就是在 cat之前被执行。 &使用不方便,因为它不接受包含参数的单个命令行字符串。 & 的替代方案是 iex ,但是我不能从 cmd.exe 使用它。实际上:
    powershell  -NoProfile -command  {iex cat  foo.txt}
    返回:
    iex cat foo.txt

    最佳答案

    Powershell 支持单引号,这让我在这种情况下节省了很多次。关于它的好处:它们是明确的且易于阅读。但请注意,变量扩展在单引号字符串中不起作用。

    powershell -NoProfile -command "cat 'foo bar.txt' | tee ps-log.txt"
    除此之外,请查看 mklement0 的答案中的有用建议。

    关于powershell - 使用 Tee 从另一个 shell 运行 PowerShell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67351394/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com