Parse Windows Command Line Output To Get PIDs - command-line

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

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

powershell $lastexitcode does not work when running batch files

I try to get the exitcode/errorlevel code from a bat file into the powershell script calling the bat file.
Althought the %ErrorLevel% is 1:
BAT file
call aCONFIGURATION
for %%f in (.\createData\*.g.sql) do sqlcmd -b -U %UserName% -P %Password% -S %sqlClonedServer% -d %sqlClonedDatabaseName% -i %%f -r1 1> NUL
echo %ERRORLEVEL%
When I do in the powershellscript
$lastexitcode its ALWAYS 0 but the %ErrorLevel% says 1
$build = "c:\my.bat"
$state = & $build
Write-Host $LASTEXITCODE
I am pulling my hairs of this crap powershell full with bugs.
I have read these links but they did not help as the result is different:
http://blogs.technet.com/b/heyscriptingguy/archive/2011/06/06/get-legacy-exit-codes-in-powershell.aspx
https://social.technet.microsoft.com/Forums/scriptcenter/en-US/05e37b8d-761b-4fd7-881e-977f114ad8d7/obtaining-errorlevel-return-codes-in-powershell-is-it-possible
How can I fix the $lastexitcode
echo %ERRORLEVEL% just writes the error code to stdout, after which the batch file exits normally.
If you want the batch script to actually return an error on exit, use exit /b [exitcode]:
call aCONFIGURATION
for %%f in (.\createData\*.g.sql) do sqlcmd -b -U %UserName% -P %Password% -S %sqlClonedServer% -d %sqlClonedDatabaseName% -i %%f -r1 1> NUL
exit /b %ERRORLEVEL%

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

How to out put the PC name that has certain process running?

I m using psexec to auto run
get.bat
tasklist | findstr pmill.exe >> dc-01\c$\0001.txt
run_get.bat
psexec #%1 -u administrator -p password -c "C:\get.bat"
pclist.txt
on all PCs on our network,
how can i get the result with PC name instead of only pmill.exe in the text file?
is there anyway i can do from powershell?
I need to get the pc name in result.
Hint plz!
Instead of psexec, try this:
#echo off
setlocal enabledelayedexpansion
for /f %%I in (pclist.txt) do (
set /p q="Checking %%I... "<NUL
ping -n 1 -w 500 %%I>NUL 2>NUL
if !errorlevel!==1 (
echo Offline.
) else (
wmic /node:%%I /user:adminuser /password:pass process where name="pmill.exe" get csname 2>NUL | find /i "%%I" >>dc-01\c$\0001.txt
echo Done.
)
)
That'll output %computername% if pmill.exe is running, or nothing otherwise.
Edit:
If you must use psexec then I suggest changing the logic of your for loop that calls psexec, something like this:
#echo off
setlocal enabledelayedexpansion
for /f %%I in (pclist.txt) do (
set pc=%%I
set /p q="Checking %%I... "<NUL
ping -n 1 -w 500 %%I>NUL 2>NUL
if !errorlevel!==1 (
echo Offline.
) else (
for /f %%z in ('psexec \\!pc! -u adminuser -p pass tasklist 2^>^&1 ^| findstr /i "pmill.exe"') do (
set /p q="pmill.exe found. "<NUL
echo !pc!>>dc-01\c$\0001.txt
)
echo Done.
)
)

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

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