windows 检查环境变量中的文本变量子字符串

wsxa1bj1  于 2023-04-22  发布在  Windows
关注(0)|答案(1)|浏览(95)

在尝试通过调用sqlcmd.exe来创建一个运行SQL脚本的批处理文件时,我试图让批处理文件检测exe的存在,并在执行之前自动将其添加到%PATH%。我可以保证它将在主机上的 * 某处 *,但不是 * 何处 *。
看看SO上的manyexamples,这表明检测字符串A是否在字符串B中的最可靠的方法是将echo输出并通过管道传输到findstr,以解决大小写不敏感等问题。
考虑到这一点,我在批处理文件中有以下内容:

@echo off

REM Ensure we can find the sql interpreter
echo Checking for SqlCmd.exe, please wait...
setlocal EnableDelayedExpansion
for /f "delims=" %%F in ('dir "%programfiles%\sqlcmd.exe" /s/b') do (
    set filepath=%%~dpF
    echo "Found SQL interpreter in: !filepath!"

    REM is it part of the PATH already?
    echo %path% | findstr /c:"!filepath!" 1>nul
    if errorlevel 1 (
        echo "SqlCmd is not part of the current ENVAR PATH, setting..."
        set path=%path%;!filepath!
    )
)

并具有以下输出;

Checking for SqlCmd.exe, please wait...
\Microsoft was unexpected at this time.

尽管文本Found SQL interpreter in:没有出现在输出中,但实际问题似乎在下一个可执行行中(通过删除它并运行进行测试):

echo %path% | findstr /c:"!filepath!" 1>nul

它似乎是echo在整行中执行,而不是echo%path%中执行,并通过管道连接到findstr
我几乎在那里,但错过了一个编码步骤/调整,让这个工作。

更新1我测试机器上的PATH变量内容为;

C:\Program Files\Common Files\Oracle\Java\javapath;C:\Program Files\Microsoft MPI\Bin\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\dotnet\;C:\ProgramData\chocolatey\bin;C:\Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\;C:\Program Files\Git\cmd;C:\Users\User\.dotnet\tools;C:\Program Files\Java\jdk-17.0.3.1\bin;C:\Users\User\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Azure Data Studio\bin
nqwrtyyt

nqwrtyyt1#

MagooMofi提供了非常有用的建议并进行了一些实验之后,我对逻辑进行了调整,使其

  • 正确解释case(我省略了/I
  • 修复了/s/b/s /b的sytax问题
  • 添加了新的setlocal EnableExtensions标志
  • 将循环变量更改为J

我也应用了其他的建议,但是它们对批处理文件的运行没有实际的影响(有效的细微差别除外)。

set path="%path;%%~dpF"

这导致%PATH%有一个前导和尾随的",这破坏了对%PATH%引用的所有引用。省略"意味着SET导致了原始错误。
相反,我放弃了设置%PATH%的尝试,直接使用找到的SqlCmd.exe引用。

@echo off

REM Ensure we can find the sql interpreter
echo Checking for SqlCmd.exe, please wait...
setlocal EnableExtensions
setlocal EnableDelayedExpansion
for /f "delims=" %%J in ('dir "%programfiles%\sqlcmd.exe" /s /b') do (
    echo SqlCmd found at %%~dpJ
    set sqlcmd="%%J"
    goto exit
)

:exit
%sqlcmd% /?

对于那些仍然希望设置%PATH%变量,并阅读变量扩展等的人,为了方便起见,下面列出了Mofi的链接;

相关问题