close existing connections during a restore
You will have to set the database to single user with roll back immediate, do the restore , then set to multi user in the same batch

ALTER DATABASE [test] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE DATABASE [test] FROM  DISK = N'V:\MSSQL2016\Backup\test.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5
ALTER DATABASE [test] SET MULTI_USER


You could get this script by setting all your options in SSMS and instead of clicking OK, Click Script at the top of the window.