© 2022 by the authors.This paper proposes a new method to determine the optimal size of a photovoltaic (PV) and battery energy storage system (BESS) in a grid-connected microgrid (MG). Energy cost minimization is selected as an objective function. Optimum BESS and PV size are determined via a novel energy management method and particle swarm optimization (PSO) algorithm to obtain minimum total cost. The MG was designed to use its own energy as much as possible, which is produced from renewable energy resources. Since it is a grid-connected system, it can demand energy from the grid within the determined limit with penalty. It differs from the studies in the literature in terms of optimizing both parameters such as PV and BESS size, being a grid-connected self-contained MG structure and controlling the grid energy by an energy management algorithm and optimizing the parameter via PSO with an energy management system (EMS). Results are compared for different PV and BESS. Moreover, effectiveness of the novel energy management method with PSO is compared with the genetic algorithm, which is the one of the well-known optimization algorithms. The results show that the proposed algorithm can achieve optimum PV and BESS size with minimum cost by using the new energy management method with the PSO algorithm.