PowerShell 스크립트를 작성할 때 특정 cmdlet에서 문제가 발생하면 비어 있지 않은 디렉터리에 대화 형 프롬프트 인 Remove-Item이 표시됩니다. 이것은 작업을 자동화하려고 할 때 치명적입니다. 작업이 실패하고 예외를 던지거나 나쁜 반환 코드를 반환하여 전체 스크립트가 응답을 기다리는 동안 잠기지 않습니다.
조치에 대한 사용자 입력을 찾는 대신 PowerShell이 자동으로 실패하도록하는 방법이 있습니까?
PowerShell 스크립트를 작성할 때 특정 cmdlet에서 문제가 발생하면 비어 있지 않은 디렉터리에 대화 형 프롬프트 인 Remove-Item이 표시됩니다. 이것은 작업을 자동화하려고 할 때 치명적입니다. 작업이 실패하고 예외를 던지거나 나쁜 반환 코드를 반환하여 전체 스크립트가 응답을 기다리는 동안 잠기지 않습니다.
조치에 대한 사용자 입력을 찾는 대신 PowerShell이 자동으로 실패하도록하는 방법이 있습니까?
답변:
참조 Get-Help about_Preference_Variables:
$ ConfirmPreference
------------------
Windows PowerShell에서 자동으로 메시지를 표시할지 여부를 결정합니다.
cmdlet 또는 함수를 실행하기 전에 확인하십시오.
...
없음 : Windows PowerShell이 자동으로 프롬프트되지 않습니다.
특정 명령의 확인을 요청하려면
cmdlet 또는 함수의 Confirm 매개 변수
그래서:
> $ConfirmPreference = 'None'
Remove-ADUser(서버 2012R)
좋아, 이것은 정말로 추악하지만 거룩한 겨자는 그것을 "작동한다".
이슈 :
이것은 간단한 경우 (현재 환경에서 많은 일을하지 않는 명령)에서만 작동합니다. 복잡한 것을 테스트하지 않았습니다
$MyPS = [Powershell]::Create()
$MyPS.Commands.AddCommand("Remove-Item")
$MyPS.Commands.AddParameter("Path", "D:\Temp\t")
$MyPS.Invoke()
산출:
Commands
--------
{Remove-Item}
{Remove-Item}
Exception calling "Invoke" with "0" argument(s): "A command that prompts the user failed because the host program or the
command type does not support user interaction. The host was attempting to request confirmation with the following
message: The item at D:\Temp\t has children and the Recurse parameter was not specified. If you continue, all children
will be removed with the item. Are you sure you want to continue?"
At line:19 char:1
+ $MyPS.Invoke()
+ ~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CmdletInvocationException
두 가지 기술을 제안합니다
a) 추가 -force
b) 추가 -errorAction silently continue
이것이 특정 매개 변수를 지원하는 cmdlet을 조사하는 방법입니다.
Get-Command | where { $_.parameters.keys -contains "erroraction"}
-errorAction SilentlyContinue입니다 -ea 0.
Remove-Item빠르게 실패하려면 어떻게해야 합니까?"라는 질문의 이름을 바꿔야한다고 생각합니다.