powershell makefile 无法识别 get-childitem 命令

powershell makefile not recognizing get-childitem command

我正在尝试使用 make 的 powershell 版本来简化我需要多次 运行 的一些命令。其中一个这样的命令是这样的:

get-childitem -file | where {($_.extension -ne ".tex") -and ($_.extension -ne ".pdf") -and ($_.name -ne "Makefile")} | remove-item

因此我在 makefile 中设置如下:

clean:
        get-childitem -file | where {($_.extension -ne ".tex") -and ($_.extension -ne ".pdf") -and ($_.name -ne "Makefile")} | remove-item

当我 运行 make clean 但是我得到一个错误:

get-childitem -file | where {(.extension -ne ".tex") -and (.extension -ne ".pdf") -and (.name -ne "Makefile")} | remove-item
'get-childitem' is not recognized as an internal or external command,
operable program or batch file.
make: *** [Makefile:5: clean] Error 255

为什么会出现此错误,是否允许我在 Makefile 中使用 powershell 命令,如上所示?

在 Windows 上,make 使用 cmd.exe 作为默认值 shell,而不是 PowerShell。

您可以指示make to use PowerShell by placing the following at the top of your Makefiles; adapted from :

Windows-仅,使用 Windows PowerShell:

SHELL := powershell.exe
.SHELLFLAGS := -NoProfile -Command 

# Sample target that echoes information about the PowerShell edition and version.
# Note:
#  * '@' preceding a command prevents the command itself from getting echoed.
#  * '$' has special meaning to `make` itself, so to pass a verbatim '$'
#    through to PowerShell, it must be escaped as '$$' 
.PHONY: demo
demo:
    @$$PSVersionTable

Windows-仅,使用 PowerShell(核心)7+:

SHELL := pwsh.exe
.SHELLFLAGS := -NoProfile -Command 

.PHONY: demo
demo:
    @$$PSVersionTable

跨平台,在 Windows 上使用 Windows PowerShell(并且,有必要,PowerShell(核心)7+Unix 类平台上):

ifeq ($(OS),Windows_NT)
    SHELL := powershell.exe
else
    SHELL := pwsh
endif
.SHELLFLAGS := -NoProfile -Command 

.PHONY: demo
demo:
    @$$PSVersionTable

跨平台,在所有平台上使用 PowerShell (Core) 7+:

ifeq ($(OS),Windows_NT)
    # Note: .exe is *required* on Windows; otherwise, 
    #       make.exe quietly falls back to cmd.exe
    SHELL := pwsh.exe
else
    SHELL := pwsh
endif
.SHELLFLAGS := -NoProfile -Command 

.PHONY: demo
demo:
    @$$PSVersionTable

注:

  • 假设是pwsh / pwsh.exe, PowerShell (Core)CLI,可以位于 $env:PATH,官方安装程序确保了这一点,但如果需要,您可以使用完整路径。

    • 注意:如前所述,在 Windows 上,您 必须 在文件名/路径中包含 .exe。如果 make 找不到可执行文件,它会悄悄回退到默认值 shell(Windows 上的 cmd.exe,类 Unix 平台上的 /bin/sh)。
  • 内置 Windows PowerShell CLI,powershell.exe,默认为 $env:PATH