Thanks for the reply Luc,
However if it is just one line connect to the ESX host it works, somehow it doesn't work in the loop ?
Initially I have logged on to the VCenter server and then execute the script that you created but it is all returning failed, the credentials has always been right when I check manually.