This paper is devoted to the analysis of problems of optimal control of ensembles governed by the Liouville (or continuity) equation. The formulation and study of these problems have been put forward in recent years by R.W. Brockett, with the motivation that ensemble control may provide a more general and robust control framework.Following Brockett's formulation of ensemble control, a Liouville equation with unbounded drift function, and a class of cost functionals that include tracking of ensembles and different control costs is considered. For the theoretical investigation of the resulting optimal control problems, a well-posedness theory in weighted Sobolev spaces is presented for the Liouville and transport equations. Then, a class of non-smooth optimal control problems governed by the Liouville equation is formulated and existence of optimal controls is proved. Furthermore, optimal controls are characterised as solutions to optimality systems; such a characterisation is the key to get (under suitable assumptions) also uniqueness of optimal controls.