2014-12-08 3 views
2

나는 같은 명령을 실행하고 싶습니다.실행 배치 파일

NB : 배치 파일의 이름은 각 매개 변수와 마찬가지로 변수에 보관됩니다.

function Escape-StringForCmd($a) 
{ 
    if(($a -like '*"*') -or ($a -like '* *')) 
    { 
     ('"{0}"' -f ($a -replace '"','""')) 
    } 
    else 
    { 
     $a 
    } 
} 

$batch = "myBatchFile.bat" 
$p1 = "param1" 
$p2 = "param2" 
$p3 = "parameter 3" 

$batch = Escape-StringForCmd($batch) 
$p1 = Escape-StringForCmd($p1) 
$p2 = Escape-StringForCmd($p2) 
$p3 = Escape-StringForCmd($p3) 

pushd \\myServer\share\scripts 

cmd.exe /c $batch $p1 $p2 $p3 
#above fails; no error returned; I think because cmd doesn't like the UNC path, so reverts to the system directory 

Start-Process "cmd.exe" -ArgumentList "/c",$batch,$p1,$p2,$p3 -NoNewWindow -Wait -WorkingDirectory "\\myServer\share\scripts" 
#above also fails; not sure why as looks healthy when running outside of ps1 file 

popd 

출력을 캡처하는데도 관심이 있습니다. 현재 배치 파일이 실행되고 있지는 않지만 초기에는 집중적으로 살펴 보겠습니다.

아직까지은 작동하지 않아도 작동하지 않아야합니다 (단, 아래 링크 참조). start-process으로 보이거나 단순히 cmd.exe /c으로 작동해야합니다. 잠깐 그 방법을 시도해 보라.

ProcessStartInfo를 솔루션 : Powershell: Capturing standard out and error with Process object

답변

1

는 호출 표현을이 사용할 수없는 이유가 있나요? *>&1

$MyCmd = "$batch $p1 $p2 $p3 *>&1" 

$ReturnOutput = Invoke-Expression $MyCmd 

출력 스트림 STDERR 표준 출력에서 ​​모든 출력을 둔다. 나는 전에`호출-Expression` 건너하지 않는 게 좋을 - - 아래의 해킹과 함께 JNK의 대답 @ 사용

More info on redirection operators here.

+0

최고 작동하도록하는 방법을 발견 덕분에 . 주의 :이 작업을 수행하려면 로컬 디렉토리 (예 : ". \ $ batch")에서 일괄 처리를 실행하고 싶다는 명확한 내용도 포함시켜야합니다. – JohnLBevan

+0

경로의 올바른 지점. – JNK

+0

실제로 - 로컬 배치에서 테스트 중임을 깨달았습니다. 이것은 UNC 경로 문제로 여전히 어려움을 겪고 있습니다. 배치 스크립트가 실행되지만 스크립트는 현재 UNC 경로 (예 : powershell의 이전 pushd 표현식)에서 실행되지 않습니다. 슬프게도 나는 배치 파일의 내용을 바꿀 수 없다 ... 더 이상의 생각은? – JohnLBevan

2

, 나는이

$tempBatchName = ".\~myTempBatchFile.bat" #put this in a variable so we can easily amend if required 

" 
pushd \\myServer\share\scripts 
$batch $p1 $p2 $p3 
popd 
" | out-file $tempBatchName -encoding ascii 

$MyCmd = ("{0} *>&1" -f $tempBatchName) 

$ReturnOutput = Invoke-Expression $MyCmd 
$ReturnOutput | out-file ("{0}.log" -f $tempBatchName) 
remove-item $tempBatchName