Writing output from netstat and findstr to text file - windows

I am currently having a problem writing the output of a netstat and findstr command to a text file. The command works fine itself when not having it's output being written to a file (netstat -a | findstr "ESTABLISHED"), or when only the netstat command is used (netstat -a >> task3.txt).
This is the command I've written which does not write to the file: netstat -a | findstr "ESTABLISHED" >> task3.txt.

This will run in a windows cmd command line or batch-file. If you are on a supported Windows system, PowerShell is available.
powershell -NoLogo -NoProfile -Command ^
"Get-NetTCPConnection | Where-Object { $_.State -eq 'Established' } >>'.\task9.txt'"

Related

keep 100 newest file in a directory - windows script porting

Hi: I have a cronjob in linux that keeps last 100 files in a directory, now I need to port it on windows.
my linux job is the following:
# sort by time, 1 per line | get files over 100th | delete those
$ ls -1t \my\path\tmp | tail --lines=+100 | xargs rm -f
and it's run once per day
Now I'm doing
REM get files olther than 2D, delete
forfiles /d -2 /p "C:\my\path\tmp" /c "cmd /c Del #path"
that just deletes files older than 2 days, but I'd like not to delete files if total number is not too big (<100)
I realize this is not as cryptic and magical as using a for loop, but it works. When you are satisfied that the correct files will be deleted, remove the -WhatIf from the Remove-Item cmdlet.
powershell -NoLogo -NoProfile -Command ^
"Get-ChildItem -File |" ^
"Sort-Object -Property LastWriteTime -Descending |" ^
"Select-Object -Skip 100 |" ^
"Remove-Item -WhatIf"
Powershell runs on Linux and Mac as well. https://github.com/powershell/powershell

powershell command output logging in batch script

I need to write this command to a bat file in a specific location:
echo PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "C:\Users\ADMINI~1\AppData\Local\Temp\2\StartupLog.txt" >> c:\myscript.bat
When I run this command it will only write PowerShell -Command "Set-ExecutionPolicy Unrestricted in myscript.bat.
I need to write the full command with the output file logging. Is this possible to do this?
Thanks!
Read Syntax : Escape Characters, Delimiters and Quotes and apply it as follows:
echo PowerShell -Command "Set-ExecutionPolicy Unrestricted" ^>^> "C:\Users\ADMINI~1\AppData\Local\Temp\2\StartupLog.txt" >> c:\myscript.bat
Proof (copy & paste from a cmd window, so lines are wrapped):
d:\bat> type myscript.bat
The system cannot find the file specified.
d:\bat> echo PowerShell -Command "Set-ExecutionPolicy Unrestricted" ^>^> "C:\Users\ADMINI~1\
AppData\Local\Temp\2\StartupLog.txt" >> myscript.bat
d:\bat> type myscript.bat
PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "C:\Users\ADMINI~1\AppData\Local\T
emp\2\StartupLog.txt"
d:\bat>

Shell script to get IPV4 address dynamically and add to route table using cygwin console for windows

I am writing a shell script which runs on cygwin console for windows, my scritp looks like this
#!/usr/bin/bash
cmd /c start /d "C:\cygwin\bin" ipconfig | findstr /R /C:"IPv4 Address"
ipconfig #to print
route add 10.2.139.1 192.168.104.1
But when i execute this script on cygwin console it shows below error and even i changed to ipconfig \all it doesn't work
Error: unrecognized or incomplete command line.
USAGE:
ipconfig [/allcompartments] [/? | /all |
i am trying to get ip address dynamically by executing the script and adding to the route table
Thanks,
Rohith
I don't know why you did this with cygwin instead of cmd.exe, what you use it for and why use start, but, all you missing is one option /b:
cmd /c start /d "C:\cygwin\bin" /b ipconfig | findstr /R /C:"IPv4 Address"
And start is redudant as follows:
cmd /c ipconfig | findstr /R /C:"IPv4 Address"
/b just suppresses the newly created cmd.exe background window.

Not able to capture output by runas command

I have to automate test cases.
Tasks:-
Step:-Open administrative command prompt from powershell.
Step:-Execute a batch file on the administrative command prompt.
Step:-Batch file includes some set of commands, including a execution of an exe.
For Example:- runas /user:administrator /savecred someCmd.exe >>D:\output.txt
Step:-Capture output of the exe in a variable for verification of the output.
i have used "
start-process -verb runas cmd.exe $param" cmdlet for opening administrative command prompt(Step 1).
Where $param contains the batch file to be executed.
Problem Statement:- When batch file executes the runas command mentioned above, it opens a new command prompt and the output is displayed in the prompt and it closes itself.
i am not able to capture the output(not getting written in the output.txt) based on which i have to do some verification.
you can use the the output redirection from the batch :
$params="/C ipconfig /all 2>&1 >>c:\temp\test.txt"
start-process -verb runas cmd.exe $params
gc c:\temp\test.txt
I ended up creating a wrapper batch file OutputWrapper.bat that takes at least two arguments:
1) output file
2) command
3) [optional] arguments
#ECHO OFF
IF "%2" == "" GOTO usage
SET OUTPUTFILE=%1
SET COMMAND=%2
SET ARGS=
SHIFT /2
:loop1
IF "%2"=="" GOTO exec
SET ARGS=%ARGS% %2
SHIFT
GOTO loop1
:exec
ECHO Command [%COMMAND%]
ECHO Arguments [%ARGS%]
ECHO Output file [%OUTPUTFILE%]
%COMMAND%%ARGS% > %OUTPUTFILE% 2>&1
GOTO end
:usage
ECHO Usage: %~nx0 outputfile command [arguments]
:end
and calling it from PowerShell like this:
$outFile = "C:\Temp\Deploy.out";
Start-Process -FilePath .\OutputWrapper.bat -ArgumentList "$outfile","whoami.exe","/priv" -Verb RunAs -Wait
Get-Content $outFile;
Solution
Open administrative command prompt from powershell.
executed a batch file in the runas command. For example: runas /user:administrator /savecred mybatch.bat
Batch file includes some set of commands, including a execution of an exe. For example someCmd.exe >>D:\output.txt
Capture output of the exe in a variable for verification of the output.
Now the output was captured and was written into a file. My target was to capture the output of the command and this was the solution through which I solved it.
I had the same problem and solved it by the use of gsudo. It let me run the elevated command and tunneled the output back from it.
gsudo {command-to-execute}
Improvement on Loïc MICHEL's answer, as without -Wait, it's likely that Get-Content will run before the process has finished. As the output isn't written until the process ends, Get-Content fails as the file does not exist.
$param = "ipconfig /all"
$args = "/C $param 2>&1 > C:\temp\test.txt"
Start-Process -FilePath cmd.exe -ArgumentList $args -Verb RunAs -Wait
Get-Content -Path C:\temp\test.txt
Alternatively, using powershell.exe instead and a random file in the temporary directory for the OS:
$CommandWithParameters = "gpresult /scope computer /z"
$OutputFile = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName())
$Arguments = ("{0} 2>&1 > {1}" -f $CommandWithParameters, $OutputFile)
Start-Process -FilePath powershell.exe -ArgumentList $Arguments -Verb RunAs -Wait
Get-Content -Path $OutputFile
Using powershell.exe will save the output file using UCS-2 LE BOM encoding. If you use cmd.exe, the encoding will be ANSI.

PowerShell in command prompt issue, 'Format-Table' is not recognized as an internal or external command, operable program or batch file

I am executing powershell script in cmd.
First i write command
C:\Windows\system32>start powershell.exe Set-ExecutionPolicy RemoteSigned
it works successfully
than for running script i write command
C:\Windows\system32>start powershell.exe C:\\Get-NetworkStatistics.ps1
It also works successfully
the problem is when i try to run the function
C:\Windows\system32>start powershell.exe Get-NetworkStatistics -computername Gbsi1 | Format-Table -autosize
it gives error that "'Format-Table' is not recognized as an internal or external command,
operable program or batch file."
here is the screenshot for it.
It runs successfully in powershell but no in cmd. Is there any issue with pipe | which i put before Format-Table
As your it is, the pipe is interpreted by CMD not powershell.
Thus, CMD will try to execute a command named Format-Table, which does not exist (outside powershell).
You can escape it using ^:
start powershell.exe Get-NetworkStatistics -computername Gbsi1 ^| Format-Table -autosize
Or by quoting the complete command line
start powershell.exe "Get-NetworkStatistics -computername Gbsi1 | Format-Table -autosize"
Note that your invocation is errnous anyhow, you need to provide the -Command option to powershell, like so:
start powershell.exe -Command "Get-NetworkStatistics -computername Gbsi1 | Format-Table -autosize"
Finally, do you really want to use start? It will open a new window, that will close immediately after the command is through. You could also use:
powershell.exe -Command "Get-NetworkStatistics -computername Gbsi1 | Format-Table -autosize"

Resources