test batch statements directly in powershell without wrapping the call in a batch file

谁都会走 提交于 2021-02-08 03:59:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!