• You are doing it right. What issue you are facing?

    Instaed of if exists use "If NOT EXISTS"

    Check for DB from sys. sysdatabases then get path from sys.master_files.