Powershell – Invoke-BatchCommand

일반 cmd 에서 잘 수행되던 명령이 Powershell 에서 똑같이 입력 했을 때 오류가 나는 경우가 있다. 대부분 특수문자가 있을때 Powershell이 특수 문자를 특정 연산자로 인식하면서 의도하지 않은 동작이 일어나는 경우 이다.
예를 들어 svn Dump file을 load하는 경우 다음과 같은 명령을 사용한다.

svnadmin load C:svntest < .test.Dump

cmd 에서는 잘 실행되지만 Powershell 에서는 다음과 같은 Error가 날 것이다.

'<' 연산자는 나중에 사용하도록 예약되어 있습니다. 위치 줄:1 문자:21 + svnadmin load test < <<<< .test.Dump + CategoryInfo : ParserError: (<:OperatorToken) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : RedirectionNotSupported

문제를 해결 하기 위해서는 Error 를 발생시킨 연산자를 Powershell이 올바르게 사용 할 수 있도록 수정 해 줘야 하는데, 번거롭고 정확히 파악 하지 못했을때에는 귀찮은 작업이 된다.

이럴 때 사용할 명령을 실제 cmd로 실행 시키는 Invoke-BatchCommand 라는 Function을 만들어 쓴다. 과정은 function parameter로 받은 문자열을 가지는 임시의 .bat 파일을 만들고 이 파일을 실행 한뒤 작업이 종료되면 .bat 파일을 지운다.

Function Invoke-BatchCommand
{
	param (
		[Parameter(Mandatory=$true)]
		$Command,
		$Path=$(Get-Location)
		)

	$TempFileName = "{0}.bat" -f [System.IO.Path]::GetRandomFileName()
	$TempFilePath = Join-Path $Path $TempFileName

	Set-Content -Path $TempFilePath -Value $Command -Force

	if (Test-Path $TempFilePath)
	{
		& $TempFilePath
		Remove-Item $TempFilePath -Force
	}
}

사용예

$executionCommand = "svnadmin load C:svntest < .test.Dump"
Invoke-BatchCommand $executionCommand

One thought on “Powershell – Invoke-BatchCommand

  1. i like this 좋은 읽기

답글 남기기

이메일 주소는 공개되지 않습니다.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.