How can I write an AppleScript which when run will connect to a specific WIFI network if available?
You can also use ControlPlane:


Enable "Nearby WiFi Network" from the Evidence Sources tab.
Add a nearby WiFi network rule from the Rules tab.
Add a Network Location or Run Shell Script action from the Actions tab.