使用开始过程运行cmd批处理文件

时间:2018-08-02 06:10:40

标签: powershell batch-file powershell-v4.0

我正在尝试使用Powershell中的启动进程运行CMD文件,但仍然收到错误:

'Changes847.cmd' is not recognized as an internal or external command, operable program or batch file.

我想寻求一些帮助/指导。这是我的代码。

$ScriptPath     = 'C:\Codes\Db\Changes1.cmd'
$DatabaseServer = 'TestMachine'
$DatabaseName   = 'TestDB'
$ExecuteSQL     = "$($ScriptPath) $($DatabaseServer) $($DatabaseName)"


$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "cmd.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "\c " + $ExecuteSQL
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

1 个答案:

答案 0 :(得分:0)

有多个问题。一种是$ ExecuteSQL变量,因为您没有空格等,因此其格式错误。下一个问题是@Ansgar Wiechers用\ c而不是/ c声明的。我刚刚创建了一个虚拟的cmd脚本,将参数写入文件进行测试。

@echo on
echo %~1 >> C:\temp\testcmd.txt
echo %~2 >> C:\temp\testcmd.txt

这是下面编辑过的powershell脚本。

$ScriptPath = 'C:\temp\test.cmd'
$DatabaseServer = 'TestMachine'
$DatabaseName = 'TestDB'
$ExecuteSQL = $($ScriptPath) + " " + $($DatabaseServer) + " " + $($DatabaseName)

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "cmd.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "/c " + $ExecuteSQL
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

请注意上面我所做的两个更改。我也有不同的文件路径,因此可以进行测试。在我的工作站上这可以正常工作,应该可以解决您的问题。