gpt4 book ai didi

powershell - 如何使用 powershell 中另一个函数的输出运行命令?

转载 作者:行者123 更新时间:2023-12-02 23:37:39 25 4
gpt4 key购买 nike

我有以下内容,完美运行 ps1脚本:

function Get-ScriptDirectory {
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}

$currentDir = Get-ScriptDirectory

node $currentDir/yarn.js $args

我想消除 $currentDir多变的。我正在尝试运行:
function Get-ScriptDirectory {
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}

node (Get-ScriptDirectory)/yarn.js $args

但这失败了 - 看起来像 Get-ScriptDirectory输出成为第一个参数。我试过使用引号,但这也不起作用 - 括号不再展开。

如何使用函数的输出运行命令?

最佳答案

根据以往的经验,等待 PetSerAl 毫无意义。发布答案,尽管他的指点总是受到赞赏。

您的 选项是:

  • 要么: 使用表达式来构造路径:
    node  ((Get-ScriptDirectory) + '/yarn.js') $Args
  • 或者:使用可扩展的字符串(字符串插值):
    node  "$(Get-ScriptDirectory)/yarn.js" $Args


  • 背景 :
  • (...)需要将单个表达式或命令包含在需要命令参数或子表达式的上下文中(这可能是本身需要包装在 (...) 中的命令调用,或者其计算优先级需要澄清的嵌入表达式)。
  • $(...)是 - 更灵活,但速度更慢 - 子表达式运算符:
  • 要将表达式或命令嵌入到可扩展字符串 ( "..." ) 中,您必须使用 $(...) - (...)行不通。
  • 在可扩展字符串之外,而 $(...)一般也能用,一般没必要用,除非你需要执行多条语句。
  • 对于单个表达式/命令,(...)不仅足够,而且性能更好。


  • 附加信息 :
  • 了解 PowerShell 的基本解析模式 ,见 Get-Help about_Parsing
  • 了解 PowerShell 的字符串扩展(字符串插值)规则 ,见 this answer我的。
  • 有关 的全面讨论如何在参数模式下解析未加引号的命令行标记(作为命令参数) ,见 this answer我的。
  • 关于powershell - 如何使用 powershell 中另一个函数的输出运行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51302140/

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