How to call an executable with parameters from powershell script

∥☆過路亽.° 提交于 2019-12-01 17:51:06

Don't make a command string. Simply use the call operator (&):

Write-Host 'Get data from service'

$path = 'D:\DataService'

Push-Location $path

$Date     = Get-Date
$DateFrom = $Date.ToString('yyyy-MM-dd HH:mm:ss')
$DateTo   = $Date.AddDays(-1).ToString('yyyy-MM-dd')

& ReportGen.exe -ReportType Data -DateFrom $DateFrom $DateTo

You want to use Invoke-Expression as per the comments below.

Invoke-Expression $_cmd

Original comment, which is wrong:

Did you try putting an ampersand in front. e.g.:

& $_cmd

Not sure why you are using the % characters.

%$_cmd% looks like a mixture of PowerShell and cmd syntax. The %'s have no special significance. PowerShell interprets that as the literal name of a command, which of course is not recognized. To execute the contents of the string, use

Invoke-Expression $_cmd

However, that will only work if ReportGen.exe is in the path, and cmd doesn't even get involved, because you're not calling it anywhere. If for some reason, as you say, you specifically want to execute that command with cmd, you should add cmd /c or cmd /k at the beginning. However, you don't even need to assign to a string, you can just call cmd directly:

cmd /c ReportGen.exe -ReportType Data -DateFrom $DateFrom $DateTo

/c means that cmd will exit after executing the command. /k means the cmd prompt will remain open after the command is executed. You probably want /c so that you'll return to the PowerShell prompt after executing the script.

A couple things. One, stop using Write-Host. Honestly, let this be the final time you ever use it (unless you truly need it - and know why you need it). Instead, use Write-Output - even when you know your script is going to run in the console. Second, you could also consider using the Start-Process cmdlet and its parameter -ArgumentList.

Your $DateFrom and $DateTo seem to be backwards, since you are making $DateTo set to yesterday. So unless you are going from today to yesterday you may want to adjust that. Also, you specify the from date, but just tack the to date on the end, not sure if you need to specify what it is, or if both dates are a part of the same parameter. As for running a command with arguments, use Invoke-Command with arguments comma delimited as such:

Invoke-Command -FilePath "D:\DataService\ReportGen.exe" -ArgumentList '-ReportType Data','-DateFrom $DateFrom','$DateTo'

I'd do it something like this.

$CustomProcess = New-Object System.Diagnostics.ProcessStartInfo
$CustomProcess.FileName = "ReportGen.exe"
$CustomProcess.arguments = "-ReportType Data -DateFrom $DateFrom $DateTo"
[System.Diagnostics.Process]::Start($CustomProcess)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!