A storage system is a key component of a microgrid. Over the last few years, research has been undertaken to determine optimal management of microgrid resources. Battery storage has a significant impact on the total operational cost as the lifetime of the battery reduces during charging and discharging cycles. In this paper, we propose optimal energy management of a community microgrid in which the cost function includes the degradation cost of the battery and a dynamic penalty to reflect the true operational cost. Particle swarm optimisation (PSO) is used to determine the battery control actions for real-time energy management. Several case studies are presented to demonstrate the effectiveness of the proposed framework in which the new cost function reduces electricity cost by up to 44.50% compared to a baseline method and 37.16% compared to another existing approach.