sql server - How to run sql script using powershell? -
i wanted run sql script using powershell getting error "the term 'invoke-sqlcmd' not recognized name of cmdlet, function, script file, or operable program. check t spelling of name, or if path included, verify path correct , try again."
i have found below snippet website.but 1 sql command..but wanted run sql script.
could please in modifying below sql script or better suggestion ?
sqlserver = "abcd\abc" $sqldbname = "abc_1223" $sqlquery = "select * table" $sqlconnection = new-object system.data.sqlclient.sqlconnection $sqlconnection.connectionstring = "server = $sqlserver; database =$sqldbname;uid=$sqldbname;pwd= $pwd; integrated security = true" $sqlcmd = new-object system.data.sqlclient.sqlcommand $sqlcmd.commandtext = $sqlquery $sqlcmd.connection = $sqlconnection $sqladapter = new-object system.data.sqlclient.sqldataadapter $sqladapter.selectcommand = $sqlcmd $dataset = new-object system.data.dataset $sqladapter.fill($dataset) $sqlconnection.close() clear $dataset.tables[0]
you can use code is, put sql script in here-string (string literal). in addition wrap call sql database in try/catch/finally construct ensure connections closed , disposed. finally, consider using application name in connection string give dba's clue connection related to. putting together:
try{ $sqlserver = "abcd\abc" $sqldbname = "abc_1223" #this here-string $sqlquery = @" select * table can select stuff , filter , join etc "@ $sqlconnection = new-object system.data.sqlclient.sqlconnection $sqlconnection.connectionstring = "server = $sqlserver; database =$sqldbname;application name = 'user2075017_db_call';uid=$sqldbname;pwd= $pwd; integrated security = true" $sqlcmd = new-object system.data.sqlclient.sqlcommand $sqlcmd.commandtext = $sqlquery $sqlcmd.connection = $sqlconnection $sqladapter = new-object system.data.sqlclient.sqldataadapter $sqladapter.selectcommand = $sqlcmd $dataset = new-object system.data.dataset $sqladapter.fill($dataset) $dataset.tables[0] } catch{ } finally{ $sqlconnection.close() $sqlconnection.dispose() }
Comments
Post a Comment