为 PowerShell Core 脚本使用 .pwsh 而不是 .ps1 扩展名?

Kar*_*are 2 powershell file-extension powershell-core

我正在使用PowerShellPowerShell Core并行。并非我为“大”PowerShell 编写的所有脚本都在 PowerShell Core 中运行,反之亦然。

为了避免混乱,我在考虑是否应该使用两个文件扩展名:

  • .ps1: 电源外壳
  • .pwsh: PowerShell 核心

Windows 中,扩展比在Unix系统中更重要,其中shebang(#!/bin/mytool) 有助于解决问题。

是使用两个扩展“最佳实践”还是有更好的选择?

附加.pwsh当我从命令行/终端调用脚本时,我不确定PowerShell 是否会执行脚本。

我在 Unix / Linux 上下文中发现了一个类似的问题。 https://unix.stackexchange.com/questions/182882/use-sh-or-bash-extension-for-bash-scripts

Ans*_*ers 14

添加一行

#requires -PSEdition Core
Run Code Online (Sandbox Code Playgroud)

在 PowerShell Core 脚本的开头,还有一行

#requires -PSEdition Desktop
Run Code Online (Sandbox Code Playgroud)

在常规 PowerShell 脚本的开头。

对于在两个版本中都运行的脚本,只需省略该行。

文档

-PSEdition <PSEdition-Name>

指定脚本所需的 PowerShell 版本。有效值为核心的PowerShell核心和桌面适用于Windows PowerShell。

不要使用不同的扩展名,因为这会影响功能。例如,PowerShell 不会点源脚本的扩展名不是 .ps1。