Turn On/off Automatic Graphics Switching

I’m trying to do a macro that will turn off automatic graphics switching when I am plugged in and turn it on when I am on battery. I can walk through using keystrokes to start the energy saver pref pane, tab to the checkbox, and toggle it, but that’s just strictly a toggle to the opposite of the current setting. Most of the time I am plugged in, so in that case I wouldn’t want it to toggle on when it is already off. Has anyone done something similar?