如何在 PowerShell 脚本文件中获取当前的 Node 版本?

问题描述 投票:0回答:1

我有一个脚本运行一些命令来获取令牌。它是不久前编写的,当时大多数机器都使用 Node v16。由于获取令牌的命令仅在 Node v18 中有效,因此脚本将节点更改为 18.13.0,然后“返回”到 16.20.0。但是,我现在使用 20.12.2 并且获取令牌的命令运行得很好,因此不需要更改版本。

显然,我可以简单地注释掉更改 Node 版本的行,但我想让脚本更智能一点,如果机器当前运行低于 18 的 Node 版本,请更改 Node 版本,记住机器运行时的 Node 版本运行脚本,然后将 Node 版本更改回原始版本。

为了实现这一目标,我尝试了以下方法:

$originalNodeVersion = & nvm version 2>&1
Write-Host "The current Node.js version managed by NVM is: $originalNodeVersion"

但是,这会输出一个系统警报:

适用于 Windows 的 NVM 应从 CMD 或 PowerShell 等终端运行。

所以我尝试运行

cmd.exe
来获取输出:

$originalNodeVersion = cmd.exe /c "nvm version" 2>&1
Write-Host "The current Node.js version managed by NVM is: $originalNodeVersion"

同样的警报。

然后我尝试创建一个临时

.bat
文件,然后清理它:

# Define the temporary batch file path
$tempBatchFile = [System.IO.Path]::GetTempFileName() + ".bat"

# Define the temporary output file path
$tempOutputFile = [System.IO.Path]::GetTempFileName()

# Write the batch file content
@"
@echo off
nvm version > "$tempOutputFile" 2>&1
"@ | Set-Content -Path $tempBatchFile

# Run the batch file
cmd.exe /c $tempBatchFile

# Capture the output from the file
$originalNodeVersion = Get-Content -Path $tempOutputFile -Raw

# Clean up temporary files
Remove-Item -Path $tempBatchFile
Remove-Item -Path $tempOutputFile

# Output the captured version
Write-Host "The current Node.js version managed by NVM is: $originalNodeVersion"

# Run command requiring node v18+

# Switch back to the original Node.js version using another batch file
@"
@echo off
nvm use $originalNodeVersion
"@ | Set-Content -Path $tempBatchFile

# Run the batch file to switch back
cmd.exe /c $tempBatchFile

# Clean up the last temporary batch file
Remove-Item -Path $tempBatchFile

这仍然得到相同的警告,它还告诉我我没有为其中一个命令提供必需的参数。

我希望在 shell 脚本中获取当前的 Node 版本不会那么复杂。任何能够实现结果的东西都会很好(例如,当前的 Node 版本是否保存在我可以在脚本内访问的某个全局变量中,这样我就根本不必运行

nvm version
?)

这是 Windows 11 商业机,版本 23H2,操作系统内部版本 22631.3593。

powershell node-windows
1个回答
0
投票

我错误地尝试获取

nvm
版本而不是
node
版本。使用
node
,初始脚本工作得很好(但我仍然不知道如何在 powershell 脚本中获取
nvm
版本,如果我需要的话)。

这就是我的最终结果:

$originalNodeVersion = & node --version 2>&1;
$major = [int]($originalNodeVersion.Substring(1,2))
$minor = [int]($originalNodeVersion.Substring(4.5))

if ($major -lt 18 -or ($major -eq 18 -and $minor -lt 13))
  {
    write-host "Set node to v18.13.0 required for aws codeartifact login --tool npm"
    nvm install 18.13.0
    nvm use 18.13.0
  }

# run commands needing Node 18 or above
# ...


# then
if ($major -lt 18 -or ($major -eq 18 -and $minor -lt 13))
  {
    write-host "Set node back to $originalNodeVersion"
    nvm use $originalNodeVersion
  }

# followed but cleanup script commands.

© www.soinside.com 2019 - 2024. All rights reserved.