By not being a threat, and having no strategic benefit to either side worth fighting a professional army on excellent defensive terrain.
Take a good at Switzerland and you'll notice one thing: mountains. Lots and lots of tall mountains. Mountains mean easily defended choke points. They mean peaks hiding guns and observers who can call down fire and artillery upon the valley below. Mountains mean bad, narrow roads making moving and supplying an invading army difficult. These natural defenses, and the Swiss will to defend it, makes any attack on Switzerland very costly.
There must be a strategic benefit to attacking a neutral country. The low countries of Belgium and the Netherlands were invaded because they're a nice, flat highway between France and Germany to side-step Franco-German border defenses. In contrast, Switzerland is a country of natural defenses. Attacking Switzerland is charging into the teeth of strong defenses, exactly what you don't want to do.
If one side attacks Switzerland, they have to fight not only the Swiss army in mountainous terrain, but risks the opposing side reinforcing them as well. Now you've just lengthened your lines, opened a new and costly front, while giving your enemy excellent defensive terrain.
Specifically, at the start of WWI the Swiss fully mobilized bringing about 220,000 men ready to defend Swiss neutrality. With strong ties to both the Germanic Central Powers and the French, and with it becoming clear that the Western Front would be fought in the north, it mostly demobilized.
Again when the war clouds loomed, the Swiss increased their military spending and modernized their army. Again at the start of WWII the Swiss mobilized against invasion with over 600,000 men.
While Hitler assured the Swiss he would respect their neutrality, they were no dummies and saw Germany might attempt to absorb them as a Germanic state. In 1941 Hitler would tell Mussolini:
Switzerland possessed the most disgusting and miserable people and political system. The Swiss were the mortal enemies of the new Germany.
While the Germans mulled invading Switzerland in Operation Tannenbaum, a feint in the north with the Italians attacking from the south, his professional officers didn't like their prospects. Chief of Staff of the German Army Franz Halder said:
Jura frontier offers no favorable base for an attack. Switzerland rises, in successive waves of wood-covered terrain across the axis of an attack. The crossing points on the river Doubs and the border are few; the Swiss frontier position is strong.
Despite Hitler's desire to squeeze the "pimple on the face of Europe", no invasion happened. My guess is, like many other German plans after the fall of France, it got lost in the all consuming invasion of the Soviet Union.