Added test with map for NH-3731
Fix NH-3731 by moving the try-catch-finally blocks inside the loops. This ensures that each created command is closed.