How to create a scheduled task using PowerShell

February 21, 2008

I found this insanely easy, thanks to some well written Microsoft documentation (shocking I know). If you need to create a scheduled task of an application in your PowerShell script you can call the Schtasks.exe application. Below is an example I used to create a scheduled task to run my exe every day at 1:00a.m. using the System account:

Write-Host “Creating Account Collector Scheduled Task”

Schtasks /create /sc DAILY /tn AccountCollector /tr “`”`”`”`”C:\Program Files\AMF\AMFCollector.exe`”`”`”`”” /s devsbvm01 /ru System /st 01:00:00

Write-Host “Scheduled Task Created”

That’s it, works painlessly on a local or remote server, which in my example, devsbvm01 is my remote server. Now, you might be wondering “whats with all the quotes?”. Well, I struggled for a long time trying to figure out why the scheduled task would be created but would never run. Turns out that the qoutes were being stripped out, thus causing the path to break. I know its sleazy, but turns out you need four sets of quotes in order to keep them from being stripped out! If anyone ever finds a better way, let me know but this seems to be it for now! So make sure you put those quotes in there!

Here is the link to the Microsoft tech net article that explains in great detail the Schtasks.exe application.

-Flea#


How to check if an object exists in a SQL 2005 Database

February 13, 2008

When executing some SQL code on an object in database such as a table, stored procedure, or view, it is important to check to see if these objects currently exist in the database. It is important because it makes your code more reusable, especially if multiple developers will be running it on their local databases. Here is a simple line of SQL you can run to find various objects in a SQL 2005 database.

How to check if an object exists in a SQL 2005 Database

if exists (select * from sys.objects where [object_id] = object_id(‘the_name_of_your_object’))
begin
print ‘Hello World’
end


How to check if a stored procedure exists in a SQL 2005 Database

Say your Database contained several hundred stored procedures and you wanted to know if the stored procedure usp_GetNames existed. Simply run the following example from above:

if exists (select * from sys.objects where [object_id] = object_id(‘dbo.usp_GetNames’) )
begin
print ‘Hello World’
end

How to check if a view exists in a SQL 2005 Database

What if you wanted to create a new view called dbo.vw_OldCustomers, but wanted to see if that view existed before you created it? Again, run the same SQL code above.

if exists (select * from sys.objects where [object_id] = object_id(‘dbo.vw_OldCustomers’) )
begin
— Logic to create the view and populate it
end


-Flea#