Battery energy storage is an essential component of a microgrid. The working temperature of the battery is an important factor as a high-temperature condition generally increases losses, reduces useful life, and can even lead to fire hazards. Hence, it is indispensable to regulate the temperature profile of the battery modules/packs properly in the battery energy storage during the operation. In view of this, a two-layer optimal control and operation scheme is proposed for a microgrid with energy storage. In the first layer, an optimal control model is formed to derive the optimal control policy that minimizes the control efforts, consisting of the fan speed and battery current magnitude, in order to achieve a temperature distribution reference over the battery modules. In the second layer, the system operator of the microgrid performs an optimal power flow to search for the optimal temperature distribution reference used in the first stage and the corresponding operating current of the battery that minimize the operation cost of the entire microgrid system. This two-layer scheme offers a great computational benefit that allows for large-scale integration of batteries. A case study is performed on the proposed two-layer model to illustrate its performance.