2017-12-05 7 views
0
@echo off 
SETLOCAL ENABLEDELAYEDEXPANSION 
set freePort= 
set newPort= 

REM Checking the default value in XML file located at the path 
FOR /F tokens^=4^ delims^=^" %%A in (
'type %~dp0\wlp\usr\servers\defaultServer\server.xml ^| find "httpEndpoint host="' 
) do (
    echo: Default Port in XML = %%A 
    set /a startPort=%%A 

) 
echo myCurrent port %startPort% 

:SEARCHPORT 
netstat -o -n -a | find "LISTENING" | find ":%startPort% " > NUL 
if "%ERRORLEVEL%" equ "0" (
    echo "port unavailable %startPort%" 

REM Here I want to ask user to enter a port number rather than hard-coded value ??? 
    set /a startPort=9080 
    echo myNew port %startPort% 
    GOTO :SEARCHPORT 

) ELSE (
    echo "port available %startPort%" 
    set freePort=%startPort% 
    GOTO :FOUNDPORT 
) 

:FOUNDPORT 
echo free %freePort% 

REM here I want to change the value of the httpPort in XML and save the xml file, and then launch the default browser with https:\\localhost:<freePort>MyApp ??? 


) 
@pause 

은 server.xml 내용은 다음과 같습니다 Windows 명령 인터프리터와 XML 파일을 처리사용자로부터 가치를 받아 XML 파일의 특정 값을 변경하고 브라우저를 시작하는 방법은 무엇입니까?

<server description="new server"> 

<!-- Enable features --> 
<featureManager> 
    <feature>webProfile-7.0</feature> 
    <!-- <feature>localConnector-1.0</feature> --> 
</featureManager> 

<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" --> 
<httpEndpoint host="27" httpPort="5357" httpsPort="9443" id="defaultHttpEndpoint"/> 

<!-- Automatically expand WAR files and EAR files --> 
<applicationManager autoExpand="true"/> 


<applicationMonitor updateTrigger="mbean"/> 

+0

기본적으로 XML 파일을 읽고 쓸 수있는 스크립팅 언어를 사용하는 것이 좋습니다. Powershell, Vbscript 또는 Jscript는 몇 가지 옵션입니다. 배치 파일이이를 수행하려면 무차별 대입 (brute force)을 사용해야합니다. – Squashman

+0

거의 완료되었습니다. 배치 스크립트의 xml 파일에 httpPort = "< >"의 새 값을 넣기 만하면됩니다. 아무도 간단한 몇 줄의 코드를 줄 수 있습니까 – Aryabhatta

+0

Xidel, cmdline 도구를 사용하여 XML 문서를 파싱하려고합니다. http://www.videlibri.de/xidel.html – user2956477

답변

1

끔찍한입니다. cmd.exe은 명령 및 응용 프로그램을 실행하기위한 것이지 XML 파일을 구문 분석하고 수정하는 데 사용되지 않습니다. 배치 파일을 사용하는 대신 C, C++ 또는 C#을 사용하여 실행 파일을 작성하는 것이 훨씬 더 낫습니다.

그러나, 여기에 배치 파일과 동일한 디렉토리에 저장해야하는 XML 파일 server.xml에서 환경 변수 NewPort에 할당 된 새 포트 번호로 속성 httpPort의 현재 포트 번호를 대체하기위한 주석 배치 파일입니다. 이 코드에는 여전히 속성 번호 ( httpsPort)가 다른 숫자 ( httpPort)와 다르게해야하므로 주석을 읽으십시오. 그렇지 않으면 두 숫자가 동시에 대체됩니다.

@echo off 
setlocal EnableExtensions DisableDelayedExpansion 

rem First check if the file to modify exists in directory of batch file. 
set "XmlFile=%~dp0server.xml" 
if not exist "%XmlFile%" goto EndBatch 

rem Define some environment variables which are needed later. 
set "NewPort=47680" 
set "LineNumber=" 
set "LineCount=0" 
set "TmpFile=%TEMP%\%~n0.tmp" 

rem Search for the line containing attribute httpPort and get its 
rem line number and the line itself loaded into environment variables. 

for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /L /N /C:httpPort= "%XmlFile%" 2^>nul') do (
    set "LineNumber=%%I" 
    set "PortLine=%%J" 
) 

rem If no line with attribute httpPort found, exit this batch file. 
if not defined LineNumber goto EndBatch 

rem Determine current number of attribute httpPort independent on where 
rem this attribute is specified in the XML line and replace this number 
rem in the line with the new port number as defined before. 

rem It is required for this type of number replace that the other port 
rem number for httpsPort is not the same number as current number for 
rem httpPort as in this case both numbers would be replaced by the new 
rem number. The attribute name and the equal sign cannot be included in 
rem the string substitution as used here. 

setlocal EnableDelayedExpansion 
set "PortNumber=!PortLine:*httpPort=!" 
for /F %%I in ("!PortNumber:~1!") do set "PortNumber=%%~I" 
set "PortLine=!PortLine:"%PortNumber%"="%NewPort%"!" 
endlocal & set "PortLine=%PortLine%" 

rem Make sure the temporary file used next does not already exist. 
del "%TmpFile%" 2>nul 

rem Copy all lines from XML file to a temporary file including empty 
rem lines with the exception of the line containing attribute httpPort 
rem which is copied to temporary file with the modified port number. 
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /R /N "^" "%XmlFile%" 2^>nul') do (
    set "XmlLine=%%J" 
    set /A LineCount+=1 
    setlocal EnableDelayedExpansion 
    if not !LineCount! == %LineNumber% (
     echo/!XmlLine!>>"%TmpFile%" 
    ) else (
     echo/!PortLine!>>"%TmpFile%" 
    ) 
    endlocal 
) 

rem Overwrite original file with temporary file automatically deleted on success. 
move /Y "%TmpFile%" "%XmlFile%" >nul 

:EndBatch 
endlocal 

펄 정규 표현식을 사용하여 XML 파일의 값을 대체 배치 파일/JScript의 하이브리드입니다 데이브 벤함 (Benham)에 의해 작성된 예를 JREPL.bat을 위해 사용하는 것입니다 훨씬 나아. 심지어 빈 문자열이 될 수 속성 httpPort의 현재 값이 무엇인지는 중요하지 않습니다 jrepl.bat를 사용하여

@echo off 
if not exist "%~dp0server.xml" goto :EOF 
set "NewPort=47681" 
call "%~dp0jrepl.bat" "(httpPort=[\x22']?)\d*([\x22']?)" "$1%NewPort%$2" /I /F "%~dp0server.xml" /O - 
rem JREPL.BAT v7.9 leaves behind JREPL\XBYTES.HEX in folder for temporary files. 
rd /Q /S "%TEMP%\JREPL" 2>nul 

. 여기에 사용 된 대소 문자를 구별하지 않는 Perl 정규 표현식은 값이 httpPort이고 값이 큰 따옴표 대신 단일 값으로 묶이거나 심지어는 XML 파일에 유효하지 않지만 따옴표로 묶이지 않은 속성을 처리합니다.

\x22은 검색 인수 문자열 자체가 큰 따옴표로 묶여 있기 때문에 Windows 명령 인터프리터의 문제를 방지하기 위해 여기에 사용 된 "의 16 진수 표기입니다.