programing

명령이 성공적으로 실행되었는지 확인합니다.

jooyons 2023. 8. 23. 21:47
반응형

명령이 성공적으로 실행되었는지 확인합니다.

이 작업이 성공하면 다른 명령을 실행할 수 있도록 if 문에 다음을 동봉해 보았습니다.

Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" | Foreach-Object {
        $Localdrives += $_.Path

어떻게 해야 할지 모르겠어요함수를 만들어 보기도 했지만, 함수가 성공적으로 완료되었는지 확인하는 방법도 알 수 없었습니다.

사용해 보십시오.$?자동 변수:

$share = Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'"

if($?)
{
   "command succeeded"
   $share | Foreach-Object {...}
}
else
{
   "command failed"
}

시작:

$?
   Contains the execution status of the last command. 
   It contains True if the last command succeeded and False if it failed.
...

$LastExitCode
   Contains the exit code of the last native program or PowerShell script that ran.

시도할 수 있습니다.

$res = get-WmiObject -Class Win32_Share -Filter "Description='Default share'"
if ($res -ne $null)
{
  foreach ($drv in $res)
  {
    $Localdrives += $drv.Path
  }
}
else
{
  # your error
}

또는 실패가 표준 출력을 반환하지 않는 경우 if 문에 대해 작동합니다(예외가 파이프라인을 종료하지 않는다고 가정).

if (! (Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'")) { 
  'command failed'
}

또한 이제 powershell 7(종료 예외와 함께 작동)에 or 기호 "|"이 있습니다.

Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" || 'command failed'

옵션 중 하나가 가장 적합한 경우가 있습니다.다음은 다른 방법입니다.

try {
Add-AzureADGroupMember -ObjectId XXXXXXXXXXXXXXXXXXX -RefObjectId (Get-AzureADUser -ObjectID "XXXXXXXXXXXXXX").ObjectId  -ErrorAction Stop
Write-Host "Added successfully" -ForegroundColor Green
$Count = $Null
$Count = 1
}
catch {
$Count = $Null
$Count = 0
Write-Host "Failed to add: $($error[0])"  -ForegroundColor Red
}

Try and catch를 사용하면 실패했을 때 오류 메시지가 반환될 뿐만 아니라 $count 변수에 0이라는 숫자가 할당됩니다.명령이 성공하면 $count 값이 1을 반환합니다.이때 이 변수 값을 사용하여 다음에 발생할 작업을 결정합니다.

"$error" 자동 변수를 사용할 수 있습니다.첫 번째 명령이 오류를 발생시키는지 또는 성공적으로 완료되었는지 확인합니다.

“execute first command”
if($error.count -eq 0)
{
   “execute second command”
}

나중에 오류를 지우려면 다음을 사용할 수 있습니다.$error.clear()그러면 오류 카운터가 0으로 설정됩니다.

언급URL : https://stackoverflow.com/questions/8693675/check-if-a-command-has-run-successfully

반응형