반응형
명령이 성공적으로 실행되었는지 확인합니다.
이 작업이 성공하면 다른 명령을 실행할 수 있도록 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
반응형
'programing' 카테고리의 다른 글
| JQuery 요소가 DOM에 있는지 확인하려면 어떻게 해야 합니까? (0) | 2023.08.23 |
|---|---|
| Spring @ContextXml에 적합한 위치를 지정하는 방법 (0) | 2023.08.23 |
| 팬더와 함께 Excel XML .xls 파일 읽기 (0) | 2023.08.23 |
| 두 타임스탬프 사이에 있는 타임스탬프가 있는 레코드에 대한 oracle sql 쿼리 (0) | 2023.08.23 |
| PowerShell을 사용하여 파일이 없는 폴더, 폴더가 없는 파일 또는 모든 폴더 복사 (0) | 2023.08.23 |