Home > front end >  powershell makefile not recognizing get-childitem command
powershell makefile not recognizing get-childitem command

Time:09-21

I'm trying to use the powershell version of make in order to streamline some commands that I need to run multiple times. One of these such commands goes like this:

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

I therefore set it up in the makefile as follows:

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

When I run make clean however I get an error:

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

Why do I get this error and am I allowed to use powershell commands within the Makefile as shown above?

CodePudding user response:

On Windows, make uses cmd.exe as its default shell, not PowerShell.

You can instruct make to use PowerShell by placing the following at the top of your Makefiles; adapted from this answer:

Windows-only, using 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-only, using PowerShell (Core) 7 :

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

.PHONY: demo
demo:
    @$$PSVersionTable

Cross-platform, using Windows PowerShell on Windows (and, of necessity, PowerShell (Core) 7 on Unix-like platforms):

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

.PHONY: demo
demo:
    @$$PSVersionTable

Cross-platform, using PowerShell (Core) 7 on all platforms:

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

Note:

  • The assumption is that pwsh / pwsh.exe, PowerShell (Core)'s CLI, can be located via $env:PATH, which the official installers ensure, but you can use a full path if needed.

    • Note: As noted, on Windows you must include .exe in the file name / path. If make cannot find the executable, it quietly falls back to the default shell (cmd.exe on Windows, /bin/sh on Unix-like platforms).
  • The built-in Windows PowerShell CLI, powershell.exe, is in $env:PATH by default.

  • Related