If you need to get script from T-SQL then only using xp_cmdshell.
For example scripting concreate index of concreate view with SMO and powershell (result is in @script variable, you could execute it with sp_executesql ):
DECLARE @OUTPUT TABLE (line nvarchar(max))
DECLARE @cmd VARCHAR(8000), @ps VARCHAR(8000), @psLoadAssemblies VARCHAR(8000), @script nvarchar(max) =''
DECLARE @srv nvarchar(max)='<server name>',
@ln nvarchar(max)='<login>',
@pw nvarchar(max)='<password>',
@db nvarchar(max) = '<database>',
@schemaName nvarchar(max) = '<schema>', -- without '[' ']'
@viewName nvarchar(max) = '<view name>', -- without '[' ']'
@indexName nvarchar(max) = '<index name>' -- without '[' ']'
SET @psLoadAssemblies = '[System.Reflection.Assembly]::LoadWithPartialName(''Microsoft.SqlServer.SMO'')|Out-Null;'
SET @ps='$using=''Microsoft.SqlServer.Management.Smo'';$s=new-object($using+''.Server'') $srv;$c = $s.ConnectionContext;$c.LoginSecure=$false;$c.Login=$ln;$c.Password=$pw; Write-Host ($s.Databases[$db].Views.Item($viewName,$schemaName).Indexes[$indexName].Script())'
SET @ps=REPLACE(@ps,'$srv',''''+@srv+'''')
SET @ps=REPLACE(@ps,'$ln',''''+@ln+'''')
SET @ps=REPLACE(@ps,'$pw',''''+@pw+'''')
SET @ps=REPLACE(@ps,'$db',''''+@db+'''')
SET @ps=REPLACE(@ps,'$schemaName',''''+@schemaName+'''')
SET @ps=REPLACE(@ps,'$viewName',''''+@viewName+'''')
SET @ps=REPLACE(@ps,'$indexName',''''+@indexName+'''')
SET @cmd = 'powershell -Command "'+@psLoadAssemblies+@ps+'"'
exec dev.Msg @cmd
INSERT INTO @OUTPUT
exec xp_cmdshell @cmd
SELECT @script+line FROM @OUTPUT
WHERE line is not null
PRINT @script
P.S. For those who asks why we could need such tricks: in some scenarios, e.g. "import data using third party tool", the approach "drop-recreate" works better than "enable-disable" objects, e.g. because such third party tool can call "truncate" and if your table participates in schema-bound view you will get a third party tool error (truncating table participating in indexed views throws an error, therefore we are forced to drop the view with all indexes before import and recreate it after).