问题
I am writing a batch file to automate a task using vscode where I get a powershell as my default shell.
The line if not exist build (md build)
produces errors in powershell.
When I pack the same line into a batch file called test.bat
I can call ./test.bat
and get the expected behaviour.
Is there a way to test my batch statements directly in the powershell?
回答1:
In powershell use Test-Path
:
If(!(Test-Path ".\build")){md ".\build"}
Or another way..
Cmd /c "your statement"
Get error code in $LastExitCode
回答2:
Unfortunately, passing statements to cmd.exe
via /c
is not the same as executing them in a batch file.
While in many cases it won't make a difference, there are - sadly - differences in how statements are processed interactively (which is what cmd /c ...
amounts to):
- only in batch files can you escape
%
characters as%%
- only in batch files do
for
loop variables use%%
rather than%
(e.g.,%%i
, not%i
)
For instance, the statement for %%i in (1,2,3) do echo [%%i]
- which is perfectly valid in a batch file - does not work via cmd /c
:
PS> cmd /c 'for %%i in (1,2,3) do echo [%%i]'
%%i was unexpected at this time.
Solution:
Save the statement(s) of interest to a temporary batch file, invoke it, then remove it.
This is cumbersome, but the Native module (authored by me) with its ins
(Invoke-NativeShell
) command can do the heavy lifting for you:
# Install the Native module for the current user.
PS> Install-Module Native -Scope CurrentUser
# Both command strings below would *not* work when passed to `cmd /c`
PS> ins 'for %%i in (1,2,3) do echo [%%i]'
[1]
[2]
[3]
PS> ins 'echo %%SystemDrive%% is %SystemDrive%'
%SystemDrive% is C:
来源:https://stackoverflow.com/questions/64197408/test-batch-statements-directly-in-powershell-without-wrapping-the-call-in-a-batc