Search code examples
powershellstart-process

ipconfig shortened timeout by powershell


Windows shell command ipconfig /renew "Ethernet 3" have default timeout (in case there is no DHCP response) 120 secs. Want to short this timeout to 15 secs by powershell, but it complain Error: unrecognized or incomplete command line.

powershell.exe "Start-Process 'ipconfig.exe' -ArgumentList '/renew', '"Ethernet 3"' -NoNewWindow -PassThru | % { if(-not $_.WaitForExit(15000)) { $_.Kill() } }"

Its just a slightly modified command utilizing ping.exe which work fine for me:

powershell.exe "Start-Process 'ping.exe' -ArgumentList '127.0.0.1', '-t' -NoNewWindow -PassThru | %% { if(-not $_.WaitForExit(15000)) { $_.Kill() } }"

seems that arguments are not passed correctly, what is a correct form of arguments scripting?


Solution

    • You must escape " characters that you want powershell.exe, the Windows PowerShell CLI, to see as part of the code to execute via the (positionally implied) -Command (-c) parameter.

      • Use \"[1]
    • Additionally, when running your command from a batch file, you must escape % as %%, to prevent cmd.exe from interpreting it up front.

      • You can avoid this problem by using either the full name of the cmdlet that the % alias refers to, ForEach-Object or its other, word-based alias, foreach

    Therefore (using positional parameter binding with Start-Process and a single -ArgumentList argument, optional quoting omitted):

    powershell.exe "Start-Process ipconfig.exe '/renew \"Ethernet 3\"' -NoNewWindow -PassThru | foreach { if (-not $_.WaitForExit(15000)) { $_.Kill() } }"
    

    [1] \" always works for PowerShell, but can situationally run afoul of cmd.exe's up-front parsing. See this answer for details and workarounds.