Say you created a new database AxDB_TEST2 and restored a test environment backup there.
Now you need to change the databases names so that D365FO would target a restored data.
First, you need to stop D365FO services, for example, with a similar PowerShell script.
Then you can use the following SQL script to 'exchange' two databases.
Once it is done, get the services back to life