June 29, 2012

Proper script inclusion in PowerShell

It is handy to use simple script inclusion in PowerShell called dot sourcing:
. .\include.ps1
There is a problem however. If you try to call the script from another directory that script lives in, an error occurs. include.ps1 will not be found since PowerShell uses current folder by default as a starting point.
To avoid this, script directory can be used:
$scriptDirectory = Split-Path -parent $MyInvocation.MyCommand.Definition
. $scriptDirectory\include.ps1

UPD: In newer versions script directory variable is provided on the shelf, just use $PsScriptPath variable

June 20, 2012

External program execution handling in Windows .cmd files

It is common to use .cmd or .bat files to run some simple scheduled tasks. But if you run some external .exe and it reports an error, your script will continue running. So, how to stop execution and exit with error code (usually it is any exit code except 0)? Just write next ugly line after each external program execution:
if %errorlevel% neq 0 exit /b %errorlevel%
For example:
svn update
if %errorlevel% neq 0 exit /b %errorlevel%
sqlcmd -S . -i task.sql
if %errorlevel% neq 0 exit /b %errorlevel%

June 14, 2012

Explicit datetime values in SQL server queries

It is common to type some temporary queries by hand in SQL Server Management Studio. In order to filter results by date easy to read datetime format can be used:
select * from Posts where CreationDate > '12 Apr 2012 09:07'
Time part can be omitted as well:
select * from Posts where CreationDate > '12 Apr 2012'
This format should work in most scenarios since it is difficult for SQL parser to mess with such an obvious date format. Certainly I would not recommend using it in production code.