The issues of energy scarcity and environmental harm have become major priorities for both business and human progress. Hence, it is important and useful to focus on renewable energy research and efficient utilization of distributed energy sources (DERs). A microgrid (MG) is a self-managed system that encompasses these energy resources as well as interconnected consumers. It has the flexibility to function in both isolated and grid-connected configurations. This study aims to design an effective method of power management for a MG in the two operating modes. The proposed optimization model seeks to strike a balance between energy usage, protecting the life of batteries, and maximizing economic benefits for users in the MG, with consideration of the real-time electricity price and constraints of the power grid. Furthermore, in order to accurately account for the dynamic nature of not only the stationary battery banks used as the energy storage systems (ESS) but also the built-in batteries of electric vehicles (EVs), the model is presented as a multi-objective, multiparametric and constrained problem. The solution is proposed to be found using the Lagrange multiplier theory, which helps to achieve good performance with less computational burden. Lastly, simulation results from both the isolated and grid-connected modes also demonstrate the effectiveness of the designed method.