0

I'm new to powershell and I wanted to run a cmd file from powershell ise to start the file.cmd but I can't get the actual file to start running

I'm trying to call my file.cmd to run. This is somethings I have tried to call it but it does not run the file.cmd from my powershell script. Is there something I'm missing or wrong?

Code:

$fileLocalPath = "c:\Temp\Dash\file.cmd"
Start-Process cmd.exe -ArgumentFile '.c\' $fileLocalPath -Wait
Write-Host "Command has run successfully"

if($LASTCODEEXIT -eq 0){
  Write-Host "File Ran Successfully"
} 
else {
  Write-Host "Failed to run"
}
Compo
  • 36,585
  • 5
  • 27
  • 39
  • 1
    Is there a particular reason why you're using `Start-Process` instead of just: `& cmd.exe /c $fileLocalPath`? – Mathias R. Jessen Feb 10 '23 at 14:10
  • Indeed: To synchronously execute console applications or batch files and capture their output, call them _directly_ (`c:\path\to\some.exe ...` or `& $exePath ...`), do _not_ use `Start-Process` (or the `System.Diagnostics.Process` API it is based on) - see [this answer](https://stackoverflow.com/a/51334633/45375). [GitHub docs issue #6239](https://github.com/MicrosoftDocs/PowerShell-Docs/issues/6239) provides guidance on when use of `Start-Process` is and isn't appropriate. – mklement0 Feb 10 '23 at 14:11
  • 1
    Aside from that, your [`Start-Process`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/start-process) syntax isn't correct: there's no `-ArgumentFile` parameter. – mklement0 Feb 10 '23 at 14:12
  • 1
    Also, a `Start-Process` call never sets `$LASTEXITCODE` - only direct invocation does (`& $fileLocalPath ...`) - note that you invoke batch files directly, no need to call via `cmd.exe` – mklement0 Feb 10 '23 at 14:13
  • 1
    As an aside: The PowerShell ISE is [no longer actively developed](https://docs.microsoft.com/en-us/powershell/scripting/components/ise/introducing-the-windows-powershell-ise#support) and [there are reasons not to use it](https://stackoverflow.com/a/57134096/45375) (bottom section), notably not being able to run PowerShell (Core) 6+. The actively developed, cross-platform editor that offers the best PowerShell development experience is [Visual Studio Code](https://code.visualstudio.com/) with its [PowerShell extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell). – mklement0 Feb 10 '23 at 14:19
  • I did end up removing the Start-Process and changed to the & cmd.exe /c $fileLocalPath but after publishing the question i did rerun the program and it did run the cmd all is working will be closing this – MP_Future Feb 10 '23 at 15:22

0 Answers0