@Ajay Kumar As mentioned by @Andreas Baumgarten , it is recommended to migrate from AzureRM to Az modules.
To your questions related to the error, please note that maximum run time allowed for runbook using Azure Sandbox is 3 hours. Seems the runtime has exceeded in your case. Hence , you were prompted with the mentioned error ""The job has been stopped because it reached the fair share limit of job execution more than 3 hours. For long-running jobs, it's recommended to use a Hybrid Runbook Worker. Hybrid Runbook Workers don't have a limitation on how long a runbook can execute. Refer https://learn.microsoft.com/en-us/azure/automation/automation-runbook-execution#fair-share for more details."
Kindly note if a query takes longer than the specified timeout (or default timeout, if unspecificed), it will fail with an status code of 504 Gateway Timeout which you have noticed when executing Invoke-AzureRmOperationalInsightsQuery command.
To check the execution time of your PowerShell Script, I would suggest you to check this third party article which helps to measure time taken to execute the script. Based on your execution time, you can choose to improvise your script or select hybrid runbook worker for execution.