如何将选定的字符串传递给变量?

how do i pass the selected string into a variable?

如何将命令的输出存储到变量中以供在 github-actions .yaml 中使用?

docker images --format='{{.ID}}' | select -first 1

给我:

fc6e040841a1

我在网上看到了关于 select-object 的东西..但老实说我不知道​​,只是想将图像推送到注册表...

以下命令在 powershell 中不起作用:

for /f "delims=" %a in ("docker images --format='{{.ID}}' | select -first 1") do @set "%_img%=%a"

the following cmd doesn't work in powershell:

for /f "delims=" %a in ("docker images --format='{{.ID}}' | select -first 1") do @set "%_img%=%a"

那是因为这是命令提示符语法。 具体来说() 之外的所有内容都只能在 cmd.exe 下工作。将命令结果分配给变量的 PowerShell 等价物是:

$variableName = COMMAND

将其应用于您的用例:

$imageId = docker images --format='{{.ID}}' | Select-Object -First 1

请注意 selectSelect-Object 的别名,两者可以互换使用。


编辑:虽然不像命令提示符那样需要设置变量,for 语法在 PowerShell 中在批处理脚本时仍然不同。当使用 foreach“语句”作为管道的一部分时,您可以阅读 PowerShell 的 for, foreach, and ForEach-Object constructs when you want to learn how they are used in PowerShell scripts, and watch for


虽然不属于问题的原始范围,但由于 OP 确实 提问并且我在评论中回答了问题,所以我将把 bash 等同于为了完整性以及我如何从上面使用的 PowerShell 方法中转换它:

imageId=$(docker images --format="{{.ID}}" | head -n 1)

这类似于 PowerShell 语法,但有一些变化:在赋值时从变量名中删除 $Select-Object 替换为 head。你不能用空格填充 =,你必须用 $().

对命令进行 subshel​​l