The problem of a harmonic oscillator of time-dependent frequency confined in a one-dimensional infinite square well with a moving wall is studied.It is shown that the exact solution and the Lewis invariant operator of the system can be obtained by performing two consecutive gauge transformations on the time-dependent Schrdinger equation.On the basis of the exact solution the Berry phases for the system are calculated by using the geometric concepts such as the geometric distance and geometric length of the curve.