简体   繁体   中英

Escape powershell characters inside cmd

I would like to execute a ping sweep, which is this powershell command:

$NET="192.168.111";for($i=1;$i -lt 255;$i++){$command="ping -n 1 -w 100 $NET.$i > nul 2>&1 && echo $NET.$i";start-process -nonewwindow "cmd" -argumentlist "/c $command" -redirectstandardoutput "tmp$i.txt"};cat tmp*.txt > sweep.txt

I need to do this inside cmd, I have already tried:

Wihout Quotes

powershell -c $NET="192.168.111";for($i=1;$i -lt 255;$i++){$command="ping -n 1 -w 100 $NET.$i > nul 2>&1 && echo $NET.$i";start-process -nonewwindow "cmd" -argumentlist "/c $command" -redirectstandardoutput "tmp$i.txt"};cat tmp*.txt > sweep.txt

With 1 doble quote

powershell -c "$NET="192.168.111";for($i=1;$i -lt 255;$i++){$command="ping -n 1 -w 100 $NET.$i > nul 2>&1 && echo $NET.$i";start-process -nonewwindow "cmd" -argumentlist "/c $command" -redirectstandardoutput "tmp$i.txt"};cat tmp*.txt > sweep.txt"

With 3 double quoutes

powershell -c """$NET="192.168.111";for($i=1;$i -lt 255;$i++){$command="ping -n 1 -w 100 $NET.$i > nul 2>&1 && echo $NET.$i";start-process -nonewwindow "cmd" -argumentlist "/c $command" -redirectstandardoutput "tmp$i.txt"};cat tmp*.txt > sweep.txt"""

Escaping the &&

powershell -c "$NET="192.168.111";for($i=1;$i -lt 255;$i++){$command="ping -n 1 -w 100 $NET.$i > nul 2>&1 \&\& echo $NET.$i";start-process -nonewwindow "cmd" -argumentlist "/c $command" -redirectstandardoutput "tmp$i.txt"};cat tmp*.txt > sweep.txt"

No success yet.

Thanks!

This worked for me, I used backticks before the quotes to escape. Even tho this could be accomplished with native Powershell commands but since you asked for something specific, here it is.

$NET="192.168.111"

for($i=1;$i -lt 255;$i++)
{
    $command="echo ########### && echo Pinging $NET.$i && ping -n 1 -w 100 $NET.$i 2>&1"
    start-process "cmd" -argumentlist "/c `"$command`"" -NoNewWindow -RedirectStandardOutput "tmp$i.txt"
}

while($true)
{
    if(-not (Get-Process cmd -EA SilentlyContinue))
    {
        cat tmp*.txt > sweep.txt
        break
    }
    sleep 5
}

Note that the while loop will wait for all cmd.exe processes to stop before breaking and unifying those files into sweep.txt . Remember to close any instance of cmd.exe you have opened before running this script or this loop will continue forever:D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM