I have this PowerShell script that I want to run for my angular project.
I can only get it to run the first command or I can only get it to run the first command and then immediately run the second command.
Start /wait /b rmdir node_modules /S
Start npm install /b /wait
I've looked on stack overflow and googled different stuff and have seen some good suggestions but haven't been able to get it to work correctly. It does currently run the first command and then finish.
I've tried to remove some of the parameters like /b or /S with no luck.
CodePudding user response:
Your primary problem is that you're using syntax for
cmd.exe
's internalstart
andrmdir
commands, which doesn't work in PowerShell.- While PowerShell does have commands with the same names, they're aliases of PowerShell cmdlets,
Start-Process
andRemove-Item
, and therefore require different syntax.
- While PowerShell does have commands with the same names, they're aliases of PowerShell cmdlets,
While you could fix your
Start
commands to useStart-Process
instead, there's no reason to use it to begin with, given that invoking cmdlets and (console) programs directly executes them synchronously, in the same console window, with the output streams connected to PowerShell's, by default.
Therefore:
Remove-Item -Force -Recurse node_modules # Equivalent of rmdir /S /Q node_modules
npm install
Note: In older versions of Windows, including versions of Windows 10 prior to release 20H2, file and directory removal is inherently asynchronous, so on occasion the removal may not have fully completed yet by the time Remove-Item
returns; it seems that calling via cmd /c
- cmd /c rmdir /S /Q node_modules
- lessens the chances of that happening (but still doesn't fully eliminate the problem). A reliable workaround is far from trivial, unfortunately - see this answer.
Update: As it turns out, you were actually running a batch file (.cmd
or .bat
), not a PowerShell script (.ps1
), but the above points apply analogously; the batch-file solution is:
rmdir /S /Q node_modules
npm install