Abensberg then lost its independence and became a part of the Duchy of Bavaria, and from then on was administered by a ducal official, the so-called caretaker. The castle of Abensberg was destroyed during the Thirty Years' War, although the city had bought a guarantee of protection from the Swedish general, Carl Gustaf Wrangel. During the War of the Spanish Succession emperor Leopold I, who had occupied Bavaria, granted the fief of Abensberg to count Ernst von Abensperg und Traun (1608–1668) from an Austrian noble family named Traun that now received the name of the former counts of Abensberg (who were believed to be distant relatives). After the occupation ended, he was however dispossessed.