Does the limit switch problem occur when nothing else is powered up on the machine i.e. spindle not running, stepper motors not running ?
If the answer is yes then it sounds like a bad connection or a faulty switch, if the answer is no then you may be getting induced voltage into the limits wiring.
Sorry if this seems too basic but I have seen these giving bad connections in real life situations; wires pushed too far into terminals so screw grips insulation, wire that looks like it's 'bare' but has a coating of clear lacquer, badly soldered joints that connect intermittently, wire where the insulation is intact but the metal core is broken, terminals that are tight but the wire has been inserted incorrectly (it missed the hole) and is not being clamped.