在尝试通过调用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
1条答案
按热度按时间nqwrtyyt1#
在Magoo和Mofi提供了非常有用的建议并进行了一些实验之后,我对逻辑进行了调整,使其
/I
)/s/b
到/s /b
的sytax问题setlocal EnableExtensions
标志J
我也应用了其他的建议,但是它们对批处理文件的运行没有实际的影响(有效的细微差别除外)。
这导致
%PATH%
有一个前导和尾随的"
,这破坏了对%PATH%
引用的所有引用。省略"
意味着SET
导致了原始错误。相反,我放弃了设置
%PATH%
的尝试,直接使用找到的SqlCmd.exe
引用。对于那些仍然希望设置
%PATH%
变量,并阅读变量扩展等的人,为了方便起见,下面列出了Mofi的链接;