无法通过runas命令捕获输出

时间:2014-10-07 07:59:56

标签: windows powershell batch-file scripting cmd

我必须自动化测试用例。

任务: -

  1. 步骤: - 从powershell打开管理命令提示符。
  2. 步骤: - 在管理命令提示符下执行批处理文件。
  3. 步骤:-Batch文件包含一些命令,包括执行exe。

    例如: - runas / user:administrator / savecred someCmd.exe>> D:\ output.txt

  4. 步骤:在变量中捕获exe的输出以验证输出。

  5. 我用过“ start-process -verb runas cmd.exe $ param“cmdlet用于打开管理命令提示符(步骤1)。 其中$ param包含要执行的批处理文件。

    问题陈述: - 当批处理文件执行上面提到的runas命令时,它会打开一个新的命令提示符,输出会显示在提示符中并自动关闭。 我无法捕获输出(不会在output.txt中写入),我必须根据该输出进行一些验证。

3 个答案:

答案 0 :(得分:0)

您可以使用批处理中的输出重定向:

$params="/C ipconfig /all 2>&1 >>c:\temp\test.txt" 
start-process -verb runas cmd.exe $params 
gc c:\temp\test.txt

答案 1 :(得分:0)

经过多次尝试和努力,我能够找到解决方案。

<强>解决方案: -

1 Step:-Open administrative command prompt from powershell.
2 Step:- executed a batch file in the runas command.
  For Ex:-runas /user:administrator /savecred mybatch.bat
3 Step:-Batch file includes some set of commands, including a execution of an exe.
For Example:-  someCmd.exe >>D:\output.txt
4 Step:-Capture output of the exe in a variable for verification of the output.
Now the output was captured and was written into a file.My target was to capture the output of the command and this was the solution through which i solved it.

答案 2 :(得分:0)

我最终创建了一个包装器批处理文件OutputWrapper.bat,该文件至少包含两个参数:
1)输出文件
2)命令
3)[可选]参数

@ECHO OFF

IF "%2" == "" GOTO usage

SET OUTPUTFILE=%1
SET COMMAND=%2
SET ARGS=

SHIFT /2

:loop1
IF "%2"=="" GOTO exec
SET ARGS=%ARGS% %2
SHIFT
GOTO loop1

:exec
ECHO Command [%COMMAND%]
ECHO Arguments [%ARGS%]
ECHO Output file [%OUTPUTFILE%]

%COMMAND%%ARGS% > %OUTPUTFILE% 2>&1
GOTO end

:usage
ECHO Usage: %~nx0 outputfile command [arguments]

:end

并从PowerShell中调用它:

$outFile = "C:\Temp\Deploy.out";

Start-Process -FilePath .\OutputWrapper.bat -ArgumentList "$outfile","whoami.exe","/priv" -Verb RunAs -Wait

Get-Content $outFile;