I added the following highlighted parts to make this work. It probably could use some cleanup but it's working so far. I did get some kind of regexquery() file not found error the first time I ran it, even though it created the database. But the second time I ran it there were no errors. I think maybe it just throws that error because the database didn't exist.
--Declared This
@NewName varchar(255) = NULL) --New Database Name
....
INSERT #FileListOutput
EXEC (@Sql)
END
-- Rename Database to New Name
SET @Database = @NewName
-- Does the database to restore exist and is it online? Then read the file structure...
IF convert(varchar(255), DATABASEPROPERTYEX(@Database, 'Status')) LIKE '%ONLINE%'
BEGIN
-- Get the file list on the existing database we will restore to
SELECT @Sql = 'USE ' + @Database + ' EXEC sp_helpfile',