Home > Back-end >  Using IF statement to determine if agent installation has succeeded
Using IF statement to determine if agent installation has succeeded

Time:06-09

i'm currently running following line to install agent to my vms

&  "$env:ProgramFiles\AzureConnectedMachineAgent\azcmagent.exe" connect 

and when installation goes fine trough it outputs following

time="2022-06-08T09:26:41 03:00" level=info msg="Loading AgentConfig file from: C:\\ProgramData\\AzureConnectedMachineAgent\\Config\\agentconfig.json"
time="2022-06-08T09:26:41 03:00" level=info msg="Onboarding Machine. It usually takes a few minutes to complete. Sometimes it may take longer depending on network and server load status."
time="2022-06-08T09:26:41 03:00" level=info msg="Check network connectivity to all endpoints..."
time="2022-06-08T09:26:42 03:00" level=info msg="All endpoints are available... continue onboarding"
time="2022-06-08T09:26:48 03:00" level=info msg="Successfully Onboarded Resource to Azure" VM Id=0000-0000-xxxx-xxxx

Now I would want to create some kinda statements (using IF) so I could handle errors better. I can save output to variable like $installation

$installation = &  "$env:ProgramFiles\AzureConnectedMachineAgent\azcmagent.exe" connect  

but I don't know how to utilize $installation so if the the message output equals or contains "Successfully Onboarded Resource to Azure" it would be fine, something like this (this do not work).

  if($installation -contains "Successfully Onboarded Resource to Azure"){
    Write-Output "Everything ok"
    } else {
    Write-Output "Installation failed"

    }

How should I proceed now? Can i use IF statement our should i try to switch to maybe function? I'm not Powershell wizard (yet).

CodePudding user response:

The -Contains operator looks for an exact (albeit case -insensitive) complete string match.

What will work is to either use the -like wildcard operator like this:

if ($installation -like '*Successfully Onboarded Resource to Azure*') {
    Write-Host "Everything ok" -ForegroundColor Green
}
else {
    Write-Host "Installation failed" -ForegroundColor Red
}

Or the regex -match operator:

if ($installation -match 'Successfully Onboarded Resource to Azure') {
    Write-Host "Everything ok" -ForegroundColor Green
}
else {
    Write-Host "Installation failed" -ForegroundColor Red
}
  • Related