Websphere bat files exits the batch file - deployment

I am writing scripts to automate the ear deployment to websphere and to create variables on the app.
My problem is that manageprofiles and startserver bat files exits my batch and to go to the next step I have to invoke it multiple times
Here is my script
FOR /F "tokens=*" %%i in ('type params.properties') do SET %%i
REM SET PATH=%PATH%;%AppServerPath%\bin
REM CALL setupCmdLine.bat -create -profileName %profile% -profilePath "%AppServerPath%\profiles\%profile%" -templatePath "%AppServerPath%\profileTemplates\default"
"%AppServerPath%\bin\manageprofiles" -listProfiles | findstr -i %profile% > nul:
if %ERRORLEVEL%==1 (
ECHO Creating profile %profile% on %AppServerPath%\profiles\%profile%
"%AppServerPath%\bin\manageprofiles" -create -profileName %profile% -profilePath "%AppServerPath%\profiles\%profile%" -templatePath "%AppServerPath%\profileTemplates\default"
)
ECHO Getting profile path
FOR /F "delims=" %%a IN ('manageprofiles -getPath -profileName %profile%') DO #SET PROFILEPATH=%%a
REM SET PATH=%OLD_PATH%;%PROFILEPATH%\bin
FOR /F "tokens=7 delims= " %%H IN ('serverStatus server1 ^| findstr "Application Server"') DO (
IF /I "%%H" NEQ "STARTED" (
v ECHO Starting server1
startServer server1
)
)
"%PROFILEPATH%\bin\wsadmin" -lang jython -f EEDeployer.jy "%PROFILEPATH%"
Any ideas or alternatives to check for a profile and create it if not exists then start server1 on it?

You need to CALL a batch to allow processing to return to the main batch.
If you simply execute a batch from within a batch, control is transferred, but no return is recorded.
CALL "%AppServerPath%\bin\manageprofiles" ...
should solve your problem. repeat with startserver...

Related

Grab an unknown IP from ipconfig and edit an unknown .ini line with that IP with BATCH script

Currently i have a setup where a program wants my LAN IP to attach their data to and this LAN IP are always random when i reboot my system. My LAN IP is always different as i do use a VPN so it's kind of a hazzle everytime i either change network or reboot as i do need to run the program, change it, restart it.
I do have a script that will make a variable with the correct IP, as it's always the first IPv4 Address. I did find it on this site.
set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
echo Your IP Address is: %%f
goto :eof
)
This is golden, but every .ini edit post i've found do not actually work for me as it prints the line infinetly instead of editing the line.
As the size of the .ini is unknown i do need a powershell script in order for it to work as BATCH has limitations.
One user on Stackoverflow had this code:
(Get-Content C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini) | ForEach-Object { $_ -replace 'Default NAS Address=.*','Default NAS Address=BHPAPPDGN01V' } | Set-Content C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini
The line that needs to be changed is mostly random. Well, not random, but it'll move sometimes as users can make some changes and it'll push the IP line down or up depending on the settings.
I'm a bit novice when it comes to BATCH and powershell and i haven't figured out a way to transfer information to powershell. For example, BATCH will grab the IP, make a variable, run a powershell script editing the .ini. I do remember having a code that grabbed the IP to clipboard but i cannot find it in this moment.
My current progress is
#echo off
setlocal EnableExtensions
echo Exiting PROGRAM...
taskkill /IM PROGRAM.exe
timeout /t 1 /nobreak>nul
:check
for /F %%a in ('tasklist /NH /FI "IMAGENAME eq PROGRAM.exe"') do if %%a == PROGRAM.exe goto waiting
echo Restarting PROGRAM...
start "" "%ProgramFiles%\PROGRAM\PROGRAM.exe"
timeout /t 1 /nobreak>nul
exit
:waiting
echo PROGRAM is still running. Retrying...
timeout /t 3 /nobreak>nul
goto check
I don't need setlocal EnableExtensions but i did try to get it to work and it was needed then.
Currently the script look if the program is running, if it is, kill it softly (wait for it to natively quit) then restart it. My goal is to kill it softly, edit the .ini and then restarting it with the changed made.
A pure PowerShell solution would be most likely the best for this task because of Windows command processor cmd.exe is not designed for editing files.
But here is a pure batch file solution for determining the current IPv4 address and write it into the INI file if it contains currently a different address.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "IniFile=C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini"
if exist "%IniFile%" goto GetIpAddress
echo ERROR: File missing: "%IniFile%"
echo/
pause
goto EndBatch
:GetIpAddress
set "ip_address_string=IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set "ip_address_string=IP Address"
rem The string above must be IP-Adresse on a German Windows.
for /F "tokens=2 delims=:" %%I in ('%SystemRoot%\System32\ipconfig.exe ^| %SystemRoot%\System32\findstr.exe /C:"%ip_address_string%"') do set "IpAddress=%%I" & goto IpAddressFound
echo ERROR: Could not find %ip_address_string% in output of ipconfig.
echo/
pause
goto EndBatch
:IpAddressFound
set "IniEntry=Default NAS Address"
rem Remove leading (and also trailing) spaces/tabs.
for /F %%I in ("%IpAddress%") do set "IpAddress=%%I"
rem Do not modify the INI file if it contains already the current IP address.
%SystemRoot%\System32\findstr.exe /L /X /C:"%IniEntry%=%IpAddress%" "%IniFile%" >nul
if errorlevel 1 goto UpdateIniFile
echo The file "%IniFile%"
echo contains already the line: %IniEntry%=%IpAddress%
echo/
goto EndBatch
:UpdateIniFile
for %%I in ("%IniFile%") do set "TempFile=%%~dpnI.tmp"
(for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "%IniFile%" 2^>nul') do (
set "Line=%%I"
setlocal EnableDelayedExpansion
set "Line=!Line:*:=!"
if not defined Line echo(
for /F delims^=^=^ eol^= %%J in ("!Line!") do (
set "FirstToken=%%J"
if "!FirstToken!" == "%IniEntry%" (
echo %IniEntry%=%IpAddress%
) else echo(!Line!
)
endlocal
))>"%TempFile%"
rem Replace the INI file by the temporary file, except the temporary file is empty.
if exist "%TempFile%" (
for %%I in ("%TempFile%") do if not %%~zI == 0 (
move /Y "%TempFile%" "%IniFile%" >nul
echo Updated the file "%IniFile%"
echo with the %ip_address_string% "%IpAddress%" for INI entry "%IniEntry%".
echo/
)
del "%TempFile%" 2>nul
)
:EndBatch
endlocal
Please read my answer on How to read and print contents of text file line by line?
It explains the awful slow code to update the INI file using just Windows Commands.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
echo /?
endlocal /?
findstr /?
for /?
goto /?
if /?
ipconfig /?
move /?
pause /?
rem /?
set /?
setlocal /?
See also Single line with multiple commands using Windows batch file for an explanation of operator &.
Read the Microsoft article about Using command redirection operators for an explanation of >, 2>nul and |. The redirection operator | must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with ipconfig and findstr with using a separate command process started in background with %ComSpec% /c and the command line between the two ' appended.
Mofi had a great batch solution, but he mentioned that CMD was not really designed for file output like this. So here's a pure powershell solution that should do what you want. It does borrow a bit from the powershell snippet you included in your question.
$ip = Get-NetIPAddress -InterfaceAlias "Ethernet" #| Out-File PathTo:\net.ini
$content = get-content PathTo:\net.ini | ForEach-Object { $_ -replace "172.23.*","$($ip.IPAddress)"}
$content | Set-Content PathTo:\net.ini
Obviously this depends on you knowing the Interface Alias you want to grab, but you can find that easily with Get-NetIPAddress, and it shouldn't change. You'll also need to update the path information.

How to set a variable in cmd which is a string from powershell command result?

I want to store the result of powershell command in cmd variable as String : powershell -com "(ls | select -Last 1).FullName". How to do this?
CMD does not have a straightforward way of assigning command output to a variable. If the command produces just a single line you could use a for loop
for /f "delims=" %a in ('some_command /to /run') do #set "var=%a"
However, if the command produces multiple lines that will capture only the last line. A better approach would be redirecting the output of the command to a file and then reading that file into a variable:
set "tempfile=C:\temp\out.txt"
>"%tempfile%" some_command /to /run
set /p var=<"%tempfile%"
del /q "%tempfile%"
If you literally need only the last file in a directory you don't need to run PowerShell, though. That much CMD can do by itself:
for /f "delims=" %f in ('dir /a-d /b') do #set "var=%~ff"
Beware that you need to double the % characters when running this from a batch file.
A FOR loop can provide the path to the file. If the default directory sorting order is not the result needed, specify additional command line switches on the DIR command.
FOR /F "delims=" %F IN ('DIR /B') DO (SET "THE_FILE=%~fF")
ECHO THE_FILE is "%THE_FILE%"
In a .bat file script, double the percent characters on FOR loop variables.
FOR /F "delims=" %%F IN ('DIR /B') DO (SET "THE_FILE=%%~fF")
ECHO THE_FILE is "%THE_FILE%"
The .bat file scripts can also run PowerShell scripts. It is best practice to not use aliases such as ls in scripts.
FOR /F "delims=" %%F IN ('powershell -NoLogo -NoProfile -Command ^
"(Get-ChildItem -File | Select-Object -Last 1).FullName"') DO (SET "THE_FILE=%%~fF")
ECHO THE_FILE is "%THE_FILE%"
The problem with cmd here is that I want to get the full paths for
FOLDERs NOT recursive... this dir /ad /b doesn't give full paths and
this dir /ad /b /s does it recursively... – stakowerflol 2 hours ago
That's not a problem, you can return the full file path without recursing.
If you are changing directory to the path you need to check then it's stored in %CD%
If you need the path to whee the Script itself is it's stored in %~dp0
If you want to provide an argument to specify and arbitrary path and get all of the listings it will be that argument term (EG %~1)
With all three possible options you can do the same thing:
Either
Prepend the provided variable to the output of the chosen directory enumeration method
OR
Use a For loop to get the file names at that path and show the result with the full path.
IE
Jenkins_A_Dir.bat
#(
SETLOCAL
ECHO OFF
SET "_Last="
ECHO.%~1 | FIND /I ":\" > NUL && (
SET "_CheckHere=%~1"
)
IF NOT DEFINED _CheckHere (
SET "_CheckHere=C:\Default\Path\When\No Argument\Specified"
)
)
REM Use a For loop to get everything in one variable
FOR %%A IN (
"%_CheckHere%\*"
) DO (
SET "_Last=%%A"
)
ECHO.Found "%_Last%"
REM Use `FOR /F` with DIR, and append the path to Check:
SET "_Last="
FOR /F "Tokens=*" %%A IN ('
DIR /A-D /B "%_CheckHere%\*"
') DO (
SET "_Last=%_CheckHere%\%%A"
)
ECHO.Found "%_Last%"
Of course you don't NEED to have set a variable such as _CheckHere
Instead, you can just replace all of the instances of %_CheckHere% with `%~1 instead, that would work just fine in the above examples too.
Okay, what if you just wanted to check the location the script was running in.
Then either change the above to use SET "_CheckHere=%~dp0" or Replace %_CheckHere% with %~dp0 throughout.
Okay but what if you don't want to set a variable you want to it to use the current working directory.
When then, even easier:
Jenkins_Current_Dir.bat
#(
SETLOCAL
ECHO OFF
SET "_Last="
)
REM Use a For loop to get everything in one variable
FOR %%A IN (
"*"
) DO (
SET "_Last=%%~fA"
)
ECHO.Found "%_Last%"
REM Use `FOR /F` with DIR, and let it append the current working directory to the path:
SET "_Last="
FOR /F "Tokens=*" %%A IN ('
DIR /A-D /B "*"
') DO (
SET "_Last=%%~fA"
)
ECHO.Found "%_Last%"

Folder being used for another process on batch script

I have a issue with a backup script I wrote. The backup is pretty simple. It will copy a directory to a destination path, and then zip it. I have a few If clauses to, example, delete the oldest backup if there are 5 or more .zip from previous backups.
The problem I'm facing is: after the XCOPY command has finished running I then run a PowerShell script from my Batch to zip the backup, but I get this error:
This happens becaus the .bat file is running. I've checked.
The code for both the batch and power shell script follows:
BATCH:
echo "========================================="
echo "=====| Backuping DCT Light's Files |====="
echo "========================================="
SET dct-light_src=\\w102xnk172\c$\inetpub\wwwroot\DCT_NEW
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set dct_light_startting_date=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set dct_light_startting_time=%%a%%b)
SET starttime=%dct_light_startting_date%
CD C:\Users\william_silva4\Desktop\tools_backup\dct_light\
SETLOCAL ENABLEDELAYEDEXPANSION
SET /A "N=0"
FOR /F %%f IN ('DIR /B /A:-D "*"') DO (SET /A "N=!N!+1")
IF %n% == 5 (
powershell.exe -noexit -file "C:\Users\william_silva4\Desktop\remove_oldest.ps1"
) ELSE (
IF EXIST C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\ (
MD C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\dctlight_backup
SET dct-light_dtn=C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\dctlight_backup
echo A folder for this backup already exists. Beggining overwrite...
) ELSE (
MD C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\dctlight_backup
SET dct-light_dtn=C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%starttime%\dctlight_backup\
)
)
CD C:\Users\william_silva4\Desktop\backup_completo
XCOPY %dct-light_src% %dct-light_dtn% /w /e /y /EXCLUDE:C:\Users\william_silva4\Desktop\backup_completo\exclusion.txt
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set dct_light_finished_date=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set dct_light_finished_time=%%a%%b)
SET startdate=%dct_light_finished_date%
SET starttime=%dct_light_startting_date%_%dct_light_startting_time%
SET finishedtime=%dct_light_finished_date%_%dct_light_finished_time%
CD C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%startdate%\
echo.LOG of %starttime%'s Backup>LOG_%startdate%.txt
echo.Start time: %starttime%>>LOG_%startdate%.txt
echo.Finished time: %finishedtime%>>LOG_%startdate%.txt
CD C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_%startdate%\dctlight_backup\
SETLOCAL ENABLEDELAYEDEXPANSION
SET /A "N=0"
FOR /F %%f IN ('DIR /S /B /A:-D "*"') DO (SET /A "N=!N!+1")
CD ../
echo.Files copied: %N%>>LOG_%startdate%.txt
powershell.exe -noexit -file "C:\Users\william_silva4\Desktop\zip_backups.ps1"
pause>nul
POWER SHELL:
#DCT Light's zipping
Start-Sleep -s 15
$source = "C:\Users\william_silva4\Desktop\tools_backup\dct_light"
$date = Get-Date -UFormat "%Y-%m-%d"
$destination = "C:\Users\william_silva4\Desktop\tools_backup\dct_light\dctlight_backup_$date.zip"
If(Test-path $destination) {Remove-item $destination}
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
Remove-Item $source\* -Recurse -Exclude *.zip
What I have tried to solve the problem:
Create a Master.ps1 with a list of scripts to run, where the first one is, obliviously, the backup batch file and then the zipping ps1 file.
Call the zipping ps1 file from the backup batch file on another window and then kill the batch. In this case, the first line of the zipping script was:
Start-Sleep -s 15
So I was certain that the batch was killed before I really started zipping.
None of the above worked. Any help? If nothing works I'll just schedule them as separated tasks on Windows.

Windows / Powershell get Program Version into variable

I'm close but not there. I can get the version of my application via powershell, but it's got a bunch of text along with it.
This command:
powershell -NoLogo -NoProfile -Command ^
(get-item -Path 'c:\myapp.exe').VersionInfo ^| ^
Format-List -Force | findstr "ProductVersion" > c:\version.txt
produces (in a text file):
ProductVersion : 1.6.7.0
Is it possible via a single command in powershell to split it? I can't run ps scripts in my environment. But if I could, I would run this:
$mystr = (get-item -Path 'c:\myapp.exe').VersionInfo | Format-List -Force | findstr ProductVersion
$arr = $mystr -split ": "
$arr[1]
Is there a way to put this on a single line and put it into a environment (batch) variable?
Given your provided method, with some modification, perhaps this would do it?
#Echo Off
For /F "Delims=" %%A In ('Powershell -C^
"(GI 'C:\myapp.exe').VersionInfo.ProductVersion"') Do Set "PV=%%A"
Echo=%PV%
Pause
Mayhap
| for /f "tokens=3" %%a in ('findstr "ProductVersion"') do echo %%a>filename
or
| for /f "tokens=3" %%a in ('findstr "ProductVersion"') do set "prodver=%%a"
or
| for /f "tokens=3" %%a in ('findstr "ProductVersion"') do setx prodver "%%a"
but no guarantees. Note the setx version may establish a registry entry for future process instances, not for the current instance. /m would need to be added to make it a HKLM instead of a HKCU variable (if it works)
You can also use WMIC to get version of your application :
#echo off
Title Get File Version of any Application using WMIC
Set "Version="
Set "AppFullPath=%Windir%\notepad.exe"
Call :Get_AppName "%AppFullPath%" AppName
Call :Add_backSlash "%AppFullPath%"
Call :GetVersion %Application% Version
If defined Version (
echo Vesrion of %AppName% ==^> %Version%
)
pause>nul & Exit
::*******************************************************************
:Get_AppName <FullPath> <AppName>
Rem %1 = FullPath
Rem %2 = AppName
for %%i in (%1) do set "%2=%%~nxi"
exit /b
::*******************************************************************
:Add_backSlash <String>
Rem Subroutine to replace the simple "\" by a double "\\" into a String
Set "Application=%1"
Set "String=\"
Set "NewString=\\"
Call Set "Application=%%Application:%String%=%NewString%%%"
Exit /b
::*******************************************************************
:GetVersion <ApplicationPath> <Version>
Rem The argument %~1 represent the full path of the application
Rem without the double quotes
Rem The argument %2 represent the variable to be set (in our case %2=Version)
FOR /F "tokens=2 delims==" %%I IN (
'wmic datafile where "name='%~1'" get version /format:Textvaluelist 2^>^nul'
) DO FOR /F "delims=" %%A IN ("%%I") DO SET "%2=%%A"
Exit /b
::*******************************************************************
Just use the ProductVersion property on the VersionInfo object and assign the result to an environment variable:
$ENV:MyEnvVariable = (get-item -Path 'c:\myapp.exe').VersionInfo.ProductVersion

how do i search for a file and when found set the file path to a variable in a batch script

I am trying to create a batch file that will run and open a Powershell script to then run.
this is what i have so far
#echo off
for /r C:\folder %%a in (*) do if "%%~nxa"=="2WNRN4VMS2.txt" set p=%%~dpnxa
if defined p (
echo %p%
) else (
echo File not found
Pause
)
Powershell.exe -Command "& '%p%'"
exit
That is very simple using command DIR for searching for the file recursively in folder C:\folder and all its subfolders and command FOR for assigning the drive and path of found file to an environment variable:
#echo off
for /F "delims=" %%I in ('dir /A-D /B /S "C:\folder\2WNRN4VMS2.txt" 2^>nul') do set "FilePath=%%~dpI" & goto FoundFile
echo File not found
pause
goto :EOF
:FoundFile
Powershell.exe -Command "& '%FilePath%'"
Please note that the string assigned to environment variable FilePath ends with a backslash. Use in PowerShell command line %FilePath:~0,-1% if the path of the file should be passed without a backslash at end.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
dir /?
echo /?
for /?
goto /?
pause /?
set /?