Adjust ps1 sql script as new databases are added

the below works for me, however every month (UTC) a new database is created in the format [HistoryMMYY], Im looking for a way i can change the database to the current when it changes, so when the new database [History0318] is started the loop will automatically adjust to using it, is there a way to accomplish this?
#infinite loop
    while(1)
{
$DBServer = "cdiserv1"
$databasename = "History0218"
$Connection = new-object system.data.sqlclient.sqlconnection
$Connection.ConnectionString ="server=$DBServer;database=$databasename;trusted_connection=True"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand

$SqlQuery = "SELECT IsNull(Subscriber.AcctLineCode, 'XX'), Subscriber.AcctNum, Subscriber.Name,SignalHistory.AlarmDate, Codes.Description, SignalHistory.AlarmZones, IsNull(Zones.Description, ''), Subscriber.Address, Subscriber.City, Subscriber.State, Subscriber.Zip, SignalHistory.PortNum, SignalHistory.LineNum, SignalHistory.RawData
FROM [History0218].[dbo].[SignalHistory] SignalHistory
   LEFT JOIN [SUBSCRIBER].[dbo].[Subscriber Data] Subscriber ON SignalHistory.AccountID = Subscriber.AccountID
   LEFT JOIN [SUBSCRIBER].[dbo].[Zone Lists] Zones ON SignalHistory.AccountID = Zones.AccountID AND LTRIM(SignalHistory.AlarmZones) = LTRIM (Zones.Number)
   LEFT JOIN [MISCELLANEOUS].[dbo].[Signal Codes] Codes ON SignalHistory.AlarmCode = Codes.Code
WHERE SignalHistory.AlarmDate >= DATEADD(HOUR, -1, GETUTCDATE())
ORDER BY AlarmDate"
    
$Connection.open()
$SqlCmd.CommandText = $SqlQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlCmd.Connection = $Connection
$dt = New-Object System.Data.DataTable
$SqlAdapter.Fill($dt) | Out-Null
$Connection.Close()
$dt | Export-Csv -Path Z:\OP\CSV\HIST.CSV -force -NoTypeInformation # use force if you want to overwrite the data in the CSV.

#just for butler
$DBServer = "cdiserv1"
$databasename = "History0218"
$Connection = new-object system.data.sqlclient.sqlconnection
$Connection.ConnectionString ="server=$DBServer;database=$databasename;trusted_connection=True"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand

$SqlQuery = "SELECT IsNull(Subscriber.AcctLineCode, 'XX'), Subscriber.AcctNum, Subscriber.Name,SignalHistory.AlarmDate, Codes.Description, SignalHistory.AlarmZones, IsNull(Zones.Description, ''), Subscriber.Address, Subscriber.City, Subscriber.State, Subscriber.Zip, SignalHistory.PortNum, SignalHistory.LineNum, SignalHistory.RawData
FROM [History0218].[dbo].[SignalHistory] SignalHistory
   LEFT JOIN [SUBSCRIBER].[dbo].[Subscriber Data] Subscriber ON SignalHistory.AccountID = Subscriber.AccountID
   LEFT JOIN [SUBSCRIBER].[dbo].[Zone Lists] Zones ON SignalHistory.AccountID = Zones.AccountID AND LTRIM(SignalHistory.AlarmZones) = LTRIM (Zones.Number)
   LEFT JOIN [MISCELLANEOUS].[dbo].[Signal Codes] Codes ON SignalHistory.AlarmCode = Codes.Code
WHERE SignalHistory.AlarmDate >= DATEADD(HOUR, -1, GETUTCDATE())AND (Subscriber.AcctLineCode ='DS'OR Subscriber.AcctLineCode ='DSA')
ORDER BY AlarmDate"
    
$Connection.open()
$SqlCmd.CommandText = $SqlQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlCmd.Connection = $Connection
$dt = New-Object System.Data.DataTable
$SqlAdapter.Fill($dt) | Out-Null
$Connection.Close()
$dt | Export-Csv -Path Z:\OP\CSV\HISTDS.CSV -force -NoTypeInformation # use force if you want to overwrite the data in the CSV.

   start-sleep -seconds 10

}

Open in new window

LVL 1
csePixelatedAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun KlineLead Software EngineerCommented:
Since you are connecting to the history database for that month, you do not need to include the database name in your SQL script. In the FROM clause, just remove "[History0218]."

As for the script, you should be able to build "$databasename = "History0218" " by getting the current month and year and appending them to "History".
1
oBdACommented:
Just change the assignment of the $database variables, and use them in the SQL query as well. And for the queries, you should use Here-Strings:
#infinite loop
    while(1)
{
$DBServer = "cdiserv1"
$databasename = "History$([datetime]::Now.ToString('MMyy'))"
$Connection = new-object system.data.sqlclient.sqlconnection
$Connection.ConnectionString ="server=$DBServer;database=$databasename;trusted_connection=True"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand

$SqlQuery = @"
SELECT IsNull(Subscriber.AcctLineCode, 'XX'), Subscriber.AcctNum, Subscriber.Name,SignalHistory.AlarmDate, Codes.Description, SignalHistory.AlarmZones, IsNull(Zones.Description, ''), Subscriber.Address, Subscriber.City, Subscriber.State, Subscriber.Zip, SignalHistory.PortNum, SignalHistory.LineNum, SignalHistory.RawData
FROM [$($databasename)].[dbo].[SignalHistory] SignalHistory
   LEFT JOIN [SUBSCRIBER].[dbo].[Subscriber Data] Subscriber ON SignalHistory.AccountID = Subscriber.AccountID
   LEFT JOIN [SUBSCRIBER].[dbo].[Zone Lists] Zones ON SignalHistory.AccountID = Zones.AccountID AND LTRIM(SignalHistory.AlarmZones) = LTRIM (Zones.Number)
   LEFT JOIN [MISCELLANEOUS].[dbo].[Signal Codes] Codes ON SignalHistory.AlarmCode = Codes.Code
WHERE SignalHistory.AlarmDate >= DATEADD(HOUR, -1, GETUTCDATE())
ORDER BY AlarmDate
"@
    
$Connection.open()
$SqlCmd.CommandText = $SqlQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlCmd.Connection = $Connection
$dt = New-Object System.Data.DataTable
$SqlAdapter.Fill($dt) | Out-Null
$Connection.Close()
$dt | Export-Csv -Path Z:\OP\CSV\HIST.CSV -force -NoTypeInformation # use force if you want to overwrite the data in the CSV.

#just for butler
$DBServer = "cdiserv1"
$databasename = "History$([datetime]::Now.ToString('MMyy'))"
$Connection = new-object system.data.sqlclient.sqlconnection
$Connection.ConnectionString ="server=$DBServer;database=$databasename;trusted_connection=True"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand

$SqlQuery = @"
SELECT IsNull(Subscriber.AcctLineCode, 'XX'), Subscriber.AcctNum, Subscriber.Name,SignalHistory.AlarmDate, Codes.Description, SignalHistory.AlarmZones, IsNull(Zones.Description, ''), Subscriber.Address, Subscriber.City, Subscriber.State, Subscriber.Zip, SignalHistory.PortNum, SignalHistory.LineNum, SignalHistory.RawData
FROM [$($databasename)].[dbo].[SignalHistory] SignalHistory
   LEFT JOIN [SUBSCRIBER].[dbo].[Subscriber Data] Subscriber ON SignalHistory.AccountID = Subscriber.AccountID
   LEFT JOIN [SUBSCRIBER].[dbo].[Zone Lists] Zones ON SignalHistory.AccountID = Zones.AccountID AND LTRIM(SignalHistory.AlarmZones) = LTRIM (Zones.Number)
   LEFT JOIN [MISCELLANEOUS].[dbo].[Signal Codes] Codes ON SignalHistory.AlarmCode = Codes.Code
WHERE SignalHistory.AlarmDate >= DATEADD(HOUR, -1, GETUTCDATE())AND (Subscriber.AcctLineCode ='DS'OR Subscriber.AcctLineCode ='DSA')
ORDER BY AlarmDate
"@
    
$Connection.open()
$SqlCmd.CommandText = $SqlQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlCmd.Connection = $Connection
$dt = New-Object System.Data.DataTable
$SqlAdapter.Fill($dt) | Out-Null
$Connection.Close()
$dt | Export-Csv -Path Z:\OP\CSV\HISTDS.CSV -force -NoTypeInformation # use force if you want to overwrite the data in the CSV.

   start-sleep -seconds 10

} 

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
csePixelatedAuthor Commented:
As far as i can see its working, thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.