Have you tried using the APIC-EM API? you don't even need to write an external script. Just use the API documentation on the APIC-EM webGUI.
Find the project UID:
/pnp-project
List the devices under the project:
/pnp-project/{projectId}/device
Then delete the device from the project:
/pnp-project/{projectId}/device/{deviceId}
cheers,
Seb.