How do I do set a variable in Windows command line to an IP? - command-line

Is there an easy way to grab the IP address from my service provider and put it into a variable via command prompt? Something like the following:
SET hostIP = nslookup \address
ECHO %hostIP%
Or
SET hostIP = ipconfig \address
ECHO %hostIP%

for /f "skip=1 tokens=2 delims=: " %f in ('nslookup %COMPUTERNAME% ^| find /i "Address"') do echo %f

The answer by Arun is good but I found that using NSLOOKUP generates a rogue comma after the hostname when more than one IP is assigned/associated with a given host.
However, I did find another way that resolves the (first assigned) IP from a given host name and doesn't generate the rogue comma - it uses PING. Very fast, very reliable.
for /f "tokens=2 delims=[]" %f in ('ping -4 -n 1 %COMPUTERNAME% ^| find /i "pinging"') do echo IP=%f
It generates a simple IPv4 address for the hostname into the variable IP. If you then do an ECHO %IP% it will show you the IP like:
IP=192.168.1.2
Of course, in batch scripts, you're going to need to replace the single %f with %%f. Note the carat ("^") in front of the pipe ("|") symbol, which is required in batch scripts so they don't interpret the pipe, and instead pipes the results of the ping statement to the find statement.

If you could use bash, (as in cygwin) this would easily be done using back-ticks to execute anything you want in your SET hostIP line.
As in
export hostIP = `curl 'http://whatsmyip.net' | grep '<title' | awk '{print $8}' | sed -e 's:<.*::g'`

Try a batch like this to set environment variables:
ipconfig > ipconfig.out
setx IPADDR /f ipconfig.out /a 7,13
setx IPADDR /f ipconfig.out /a 7,14
setx IPMASK /f ipconfig.out /a 8,14
Exit the command prompt and open a new one. Use SET and look for IPADDR and IPMASK, which are now persistent. To update the variables, you would have to rerun the batch and exit the command prompt. The different coordinates shown account for differences in the IPCONFIG output for Windows 2003 vs Windows 2008 (should work on XP/7 in the same way). Only a found value is written, so the line that fails does no harm as long as nothing is found. Add the gateway with:
setx IPGATE /f ipconfig.out /a 9,12

Related

Running Commands in Batch FIle

I am trying to create a batch file to run start some micro services and database
1 FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :1000') DO #ECHO TaskKill.exe /PID %%P
2 FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :1001') DO #ECHO TaskKill.exe /PID %%P
3 FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :5432') DO #ECHO TaskKill.exe /PID %%P
4 start cd "C:\Program Files\PostgreSQL\10\bin\" & pg_ctl.exe -D "c:\Program Files\PostgreSQL\10\data" start
#REM to start service
5 start javaw -jar -Dserver.port=1000 text-annotation-tool-1.0-SNAPSHOT.jar
Line 1 to 3 and Line 5 execute correctly when executed by commenting line 4.
Line 4 is to start a Postgres server in a new prompt (beacuse of the Dir change). I think the problem is with the way I have used quotes. The 'start' at the beginning and ending of line 4 serve different purpose.
Also, if I execute line 4 in different prompt, How do I close the prompt after execution (nohup equivalent)
There are two errors: You can't "pass" cd to the start command. And start has the quirk to interpret the first quoted parameter as the new window's title. So start "C:\Program Files\PostgreSQL\10\bin\" ... wouldn't work, you need to supply a dummy window title. The & also seems wrong
So you need:
start "Postgres Server" "C:\Program Files\PostgreSQL\10\bin\pg_ctl.exe" -D "c:\Program Files\PostgreSQL\10\data" start
As the full path to pg_ctl.exe is supplied, there is no need for a cd.
But if you want to define the default directory for the new process, you have to use the /D parameter:
start "Postgres Server" /D "C:\Program Files\PostgreSQL\10\bin" pg_ctl.exe -D "c:\Program Files\PostgreSQL\10\data" start
Unrelated, but: putting the Postgres data directory into c:\Program Files\ is a very bad idea. That directory has special permissions for a purpose. You should use %ProgramData% or %AppData% instead

How to trim/remove leading/left white spaces from a text file using Windows Batch?

I want to remove/trim the leading/left white space which are as a result of me hiding headers and footers from my PostgreSQL query using Windows batch. I am not sure whether these are white spaces or tabs.
My SQL query:
psql -d databasename -p portname -U username -t -f filename -o "C:\text.txt"
I am not aware of any other way to do this since my SQL is a multi line query and I am not sure if we can do this using -c.
Previous the result was something like this:
After removing the header:
So as you can see there is a white space here and I want to remove it.
Can someone please help me with this?
Have a look at the -t and -A psql parameters:
-t removes headers and footers from the results
-A switches off aligned mode (which is most likely where your whitespace is coming from - alignment into columns).
So the command should look something like the following:
psql -d databasename -p portname -U username -t -A -f filename -o "C:\text.txt"
So, basically, you shouldn't need to modify the resulting file - you can modify your psql command to get results in a format you want.
Here is an hybrid script (batch\vbscript) to trim a string left and right :
#echo off
Set "VAR= abc#abc.com "
echo My Variable before the Trim Function VAR="%VAR%"
Call :Trim "%VAR%"
echo(
echo My Variable after the Trim Function VAR="%VAR%"
pause>nul & exit
::*************************************************************************
:Trim <String>
(
echo Wscript.echo Trim("%~1"^)
)>"%tmp%\%~n0.vbs"
for /f "delims=" %%a in ('Cscript /nologo "%tmp%\%~n0.vbs"') do (
set "VAR=%%a"
)
exit /b
::**************************************************************************

Parse Windows Command Line Output To Get PIDs

I'm looking to gather only the PID value outputted when you run this netstat command:
netstat -a -o -n -p tcp | findstr -i "CLOSE_WAIT"
My intention is to use the PIDs and create a script that will run taskkill /PID pidfoundhere to remove any sockets with CLOSE_WAIT state.
#echo off
for /f "tokens=5" %%a in ('
netstat -noa -p tcp ^| find /i "CLOSE_WAIT"
') do if not "%%a"=="0" echo taskkill /pid %%a
Use for command to split the line using the spaces as delimiters, get the 5th token in the line and if there is PID, kill the process
The taskkill commands are only echoed to console. If the output is correct, remove the echo command

Windows command line program that lists open sockets of certain process

I know that on windows I can type "netstat -an" and find open tcp connections.
But there is no information about the processes that own that tcp connections.
In Linux you get this info with "lsof".
Is there a free command line program that gives this information?
On Windows 2000 and later, netstat can display the process ID for each open socket via the -o parameter, eg:
netstat -ano
See MSDN for more details:
The netstat command can now display process IDs that correspond to active TCP or UDP connections in Windows 2000
SysInternals TCPView can display process names, and has both GUI and command-line interfaces.
This will return the process ID for the process name in MSDOS
tasklist /svc | find "processName"
then you can plug that PID into netstat
netstat -ano | find "PID HERE"
I dont know how to connect it all together into a batch though. I just know how to work in the command line.
Put this script in a batch file (eg Mynetstat.bat) and give process name as argument.
Command : Mynetstat.bat <process name>
#echo off
set procName=%1
for /f "tokens=2 delims=," %%F in ('tasklist /nh /fi "imagename eq %1" /fo csv') do call :Foo %%~F
goto End
:Foo
set z=%1
echo netstat for : "%procName%" which had pid "%1"
echo -----------------------------------------------------------------------------------
netstat -ano |findstr %z%
goto :eof
:End

Need to copy the lines just before a particular string using batch file

I have a file like this:
Executing resource: D:\waste2\SPC\depks_rtl_teller_custom.spc
Executing resource: D:\waste2\SPC\ifpks_msg_incoming_cluster.spc
Failed to execute:
Executing resource: D:\waste2\SQL\casapks_batch.sql
Failed to execute:
Executing resource: D:\waste2\SQL\depks_decbatop_kernel.sql
Executing resource: D:\waste2\SQL\depks_services.sql
Failed to execute:
I need a batch file or perl script or ANT script to pick all the lines just in front of the string "Failed to execute:" and copy to a new file. Simply the failed file list I need in a new file. Please assist.
Surprise! The native Windows FINDSTR command can handle this problem quite nicely :-) There is no need for perl, or any other non-native utility.
#echo off
setlocal
::Define LF variable containing a linefeed (0x0A)
set LF=^
::Above 2 blank lines are critical - do not remove
::Define CR variable containing a carriage return (0x0D)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
setlocal enableDelayedExpansion
::regex "!CR!*!LF!" will match both Unix and Windows style End-Of-Line
findstr /rc:"!CR!*!LF!Failed to execute:" "test.txt" >"failed.txt"
type failed.txt
See What are the undocumented features and limitations of the Windows FINDSTR command? for more info.
With perl, you could do something like:
while(<>) {
print $prev if /^Failed to execute:/;
$prev = $_;
}
To execute directly from your shell, you can use the following command
perl -ne 'print $prev if /^Failed to execute:/; $prev=$_' path/to/your/file
Using tac and sed:
tac file | sed -n '/Failed to execute/{n;p;}' | tac
You could also use two grep invocations, although this is more of a hack (assuming you only have lines starting with either "failed" or "executing"):
grep -B1 '^Failed to execute' your/file | grep '^Executing'
Or
grep -B1 '^Failed to execute' your/file | grep -v '^--' | grep -v '^Failed to execute'
with PowerShell:
PS II> Select-String "Failed to execute:" c:\file.txt -co 1 | % { $_.context.Precontext }
or simply:
for /f "delims=" %%a in (c:\test.txt) do (
echo(%%a| find /i "Failed to execute:" >Nul && (
setlocal enableDelayedExpansion
echo !msg!
endlocal
)
set "msg=%%a"
)