We have created powershell scripts which runs all the scripts in specific folder.
$server = Read-Host -Prompt 'Please enter server name'
$usrname = Read-Host -Prompt 'Please enter user name'
$passwd = Read-Host -Prompt 'Please enter password' -assecurestring
$dbname = Read-Host -Prompt 'Please enter DB name'
$ScriptFolder = Read-Host -Prompt 'Please enter the folder path'
$passwd =[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwd))
$logfile = "$ScriptFolder"+"\Scripts_Log_"+(Get-
Date).ToString("yyyyMMdd")+".txt"
"$(Get-Date) : Queries to be executed for Database $dbname on $server " >> $logfile
try{
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$server;Database=$dbname;trusted_connection=true;User ID=$usrname;Password=$passwd;"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
foreach ($query in Get-ChildItem -path $ScriptFolder -Filter *.sql)
{
$qu = Get-Content $query.FullName
try{
$command = $SqlConnection.CreateCommand()
$command.CommandText = $qu
$Reader = $Command.ExecuteReader()
$Reader
"$(Get-Date) : $query - Successfully executed`n" >> $logfile
write-host "$query - Successfully executed`n" -foregroundcolor "Green"
$Reader.close()
}
catch{
write-host "Unable to execute - $query :" -foregroundcolor "Red"
write-host "$_.Message`n" -foregroundcolor "Red"
"$(Get-Date) : $query - Script failed due to:" >> $logfile
"$_.Message`n" >> $logfile
}
}
}
catch{
write-host "Login failed:" -foregroundcolor "Red"
write-host "$_.Message`n" -foregroundcolor "Red"
"$(Get-Date) : login failedn:" >> $logfile
"$_.Message`n" >> $logfile
}
$SqlConnection.Close()
write-host "All the process has been completed" -foregroundcolor "Yellow"
"$(Get-Date) : All the process has been completed" >> $logfile
But when this scripts run on DB server for which i have windows authentication then it doesnt do anything inside the for each loop and dont fail either. Is there a way that this script will work for both windows and sql authentication