Sei sulla pagina 1di 20

DOS Commands for the SQL Server DBA

By: Jeremy Kadlec | Read Comments | Related Tips: More > DBA Best
Practices
Problem
I have seen your recent tips (Introduction to Windows PowerShell for the SQL Server
DBA Part 1, Introduction to Windows PowerShell for the SQL Server DBA Part
2 and PowerShell Support in SQL Server 2008 - Invoke-Sqlcmd Cmdlet) on PowerShell
and see value in them. Unfortunately, we do not have PowerShell installed on our SQL
Servers and I am not sure when that is going to happen. Until that day arrives could
you give me some insight into valuable DOS commands that I can leverage in
administrative and research situations on my SQL Servers?
Solution
PowerShell offers a great deal of value, but if it is not installed on your SQL Servers,
then working through that process in some large organizations could take time. I would
recommend moving down that path, but until that day comes, there are some DOS
commands that can be valuable as well.
In an earlier tip (Accessing the Windows File System from SQL Server) we outlined some
options to access files and directories, so be sure to check that out. To build on those
commands let's see how to do the following:
File management
o Copy, cut, paste, move, delete, etc. files
o Create and remove directories
Troubleshooting and Research
o Gather system information - Winmsd
o Validating a machine is online after a reboot - Ping
o Active Ports - netstat
o Network cards - ipconfig
o Free disk space - master..xp_fixeddrives
o Directory structure - master..xp_subdirs
Before we go too far down this path, using these commands in SQL Server is based on
having the extended stored procedure master..xp_cmdshell enabled. In SQL Server
2000, in general this was accomplished by having SQL Server System Administrator
rights. In SQL Server 2005, the master..xp_cmdshell extended stored procedure is
enabled by using the Surface Area Configuration manager. In SQL Server 2008,
enabling the master..xp_cmdshell extended stored procedure is accomplished by
properly configuring the correct facet.

File Management
One set of logic I have used time and time again in T-SQL administrative scripts is
related to file management. Whether it is from an automated maintenance task or
backup\recovery\log shipping, managing files has been a necessity.
DOS File Management Commands
Copy and Paste Files - The xcopy command is handy when you need to copy and paste files from
one directory to another. In the example below we are copying the Test.txt file in the C:\temp
directory to the root of the C:\ drive. The /v switch verifies the file as it is written to the destination
directory, the /q suppresses the display of messages, /y switch indicates that suppresses a prompt to
overwrite an existing file and the /z switch copies the file in a mode where the file could be
restarted. This command has additional options available than the copy command related to
including subdirectories, archived files, verifying files, etc.


Cut and Paste Files - When it comes to cutting and pasting files, I prefer to use the move command.
It is a simple command with a single switch to suppress any prompting followed by the source file and
destination directory. Another alternative is to use the xcopy command listed above and then one of
the delete commands listed below for more advanced deleting techniques.


Delete Files - Deleting files is imperative to ensure disk drives to not fill up. Although disk is cheap at
some point it gets expensive to manage (people) and power the SAN\NAS\DASD devices.
Here are a few different tips that have already been written on the topic:
Maintenance task to delete old SQL Server backup files
Maintenance task to delete old SQL Server
backup files

By: Greg Robidoux | Read Comments (3) | Related
Tips: More > Maintenance
Problem
In two previous tips we discussed how to automate full backups and transaction log
backups by creating scripts that iterate through each of your databases and then
execute the backup commands. A reader requested information about how to automate
the process of deleting older backup files, so this tip explains one approach for getting
rid of older backup files that are generated.
Solution
In previous tip we took a look at using Windows Scripting (Simple way to find errors in
SQL Server error log) to read through the error log files and generate a slimmer error
file with just the error messages and the related messages that were created at the
same time. In this tip, we will also be using Windows Scripting to go through each of
the subfolders to find files older than a certain timeframe and then delete these files.
Here is the VBScript code. This was pulled together from a few different code snippets
found on the internet.
There are two parameters that need to be adjusted:
iDaysOld - specify how many days old the files need to be for the script to delete
them
strPath - this is the folder where the backups are created.
iDaysOld = 7
strPath = "C:\BACKUP"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strPath)
Set colSubfolders = objFolder.Subfolders
Set colFiles = objFolder.Files

For Each objFile in colFiles
If objFile.DateLastModified < (Date() - iDaysOld) Then
MsgBox "Dir: " & objFolder.Name & vbCrLf & "File: " & objFile.Name
'objFile.Delete
End If
Next


For Each objSubfolder in colSubfolders
Set colFiles = objSubfolder.Files
For Each objFile in colFiles
If objFile.DateLastModified < (Date() - iDaysOld) Then
MsgBox "Dir: " & objSubfolder.Name & vbCrLf & "File: " & objFile.Name
'objFile.Delete
End If
Next
Next
Setup
To use this script first create a new text file and copy and paste the above
code. Save this new file as C:\DeleteBackupFiles.vbs or whatever you would like
to call it.
Create another new text file and copy and paste the code below. .(If you rename
the file or place it in another folder use this instead of the info below.) Save this
new file as C:\DeleteBackupFiles.bat.
C:\DeleteBackupFiles.vbs
Note: As a safeguard the script just displays a message box with the folder and file
name. To actually delete the files you will need to remove the single quote ' before the
two delete lines.:
'objFile.Delete
At this point you can just run the BAT file and this will delete any files in the subfolders.
The way this works is it will delete any files that it finds in the subfolders after the
starting point. It does not care about what kind of files they are, it will delete all files
that are older than the timeframe specified. The script also will delete files in the root
folder and any files one subfolder level deep. It does not go beyond the first subfolder
level.
So if you specify your backups to be in "C:\Backup" this script will delete all files in the
"C:\Backup" folder as well as any files in the first level subfolders as long as the date of
the file is older than specified.
This can now be setup as a scheduled job by calling the BAT file. SQL Server Agent
doesn't like running VBScript files directly, so by using a BAT file you can set this up as a
scheduled job.
Next Steps
Use this script as is or modify this to have additional options that meet your
needs such as specifying certain types of files.
The script uses the DateLastModified property, but this could also be changed to
the DateCreated property.
Modify the script to add some logging, so you can see what has been deleted.
The maintenance plans use XP_DELETE_FILE (2005) and SQLMaint (2000) to
delete the older files. You could look at these options as well.
Take a look at the other backup scripts to automate your entire backup process.
o Simple script to backup all databases
o Automating Transaction Log Backups for All Databases

CLR function to delete older backup and log files in SQL Server
CLR function to delete older backup and log
files in SQL Server

By: Greg Robidoux | Read Comments | Related Tips: More > Backup
Problem
In a previous tip we looked at how to put together a CLR function for sorting text
data. In addition, we have also written tips about how to mimic the functionality of
maintenance plans without having to use a maintenance plan. In one of these previous
tips, "Maintenance task to delete old backup files" we outlined how to delete older
backup files by using a VB Script. To take this deleting of older files a step further, this
tip will look at this same task to remove older backup and log files, but this time using a
CLR function.
Solution
If you have not yet built a CLR function, please refer to this tip for what needs to be
done for the initial setup.
CLR Functions - Getting started with a string sort function

In this CLR function we are going to pass in a few parameters such as:
File path
Days to keep files
File Extension
and return a count of the number of files that were deleted.

Step 1 - CLR code
The first thing we need to do is to write the CLR code for this. This could be written in
either C#.NET or VB.NET. In this example we are using VB.NET.
The following code has a Class (CLRFunctions) and a Function (DeleteFiles). The
function takes three parameters and returns an integer value.
Copy and save the code below in a file called: C:\CLRFunctions.vb
Imports System.IO

Public Class CLRFunctions

Public Shared Function DeleteFiles(sPath As String, iDaysToKeep As Integer, sFi
leExtension As String) As Integer

Dim arrFiles As Array
Dim dateToday As Date
Dim myFileInfo As FileInfo
Dim myDirectoryInfo As DirectoryInfo
Dim iFileCount As Integer

Try
iFileCount = 0

myDirectoryInfo = New DirectoryInfo(sPath)

arrFiles = myDirectoryInfo.GetFiles()

dateToday = DateAdd("d", -iDaysToKeep, Today)

For Each myFileInfo In arrFiles
If myFileInfo.Extension = sFileExtension And myFileInfo.LastWriteTime
< dateToday Then
myFileInfo.Delete()
iFileCount = iFileCount + 1
End If
Next

Return iFileCount

Catch
Return 0
End Try

End Function

End Class

Step 2 - Compile CLR Code
In order to use this code, the code has to be compiled first.
The following command is run from a command line to compile the CLR code using the
vbc.exe application. This is found in the .NET 2.0 framework directory. This may be
different on your server or desktop. Also, this code should be compiled on the machine
where the code will run.
So from a command line run a command such as the following:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\vbc /target:library
C:\CLRFunctions.vb
The code should now be compiled in a file called: C:\CLRFunctions.dll

Step 3 - Create Assembly and Function
After the code has been compiled you need to create the assembly and the function with
SQL Server. To do this, run these commands in the database where you want to use the
function.
The assembly ties an internal object to the external DLL that was created and the
function is similar to a normal SQL Server function.
For the function you will see three components that are referenced
CLRFunctions.CLRFunctions.DeleteFiles.
CLRFunctions - the assembly reference
CLRFunctions - the class reference in the VB code
DeleteFiles - the function reference in the VB code
CREATE ASSEMBLY CLRFunctions FROM 'C:\CLRFunctions.dll'
WITH PERMISSION_SET = UNSAFE
GO

CREATE FUNCTION dbo.DeleteFiles
(
@FolderPath AS NVARCHAR(100),
@DaysToKeep AS integer,
@FileExtension AS NVARCHAR(50)
)
RETURNS integer
AS EXTERNAL NAME CLRFunctions.CLRFunctions.DeleteFiles
GO
If you get error messages when trying to compile the code you may need to alter the
database using the following command and then try again to create the assembly and
the function.
ALTER DATABASE test1 SET trustworthy ON

Step 4 - Test It
To test the function, run the following SELECT statement based on the values you want
to pass into the function.
In this example we are deleting files in the "C:\Backups" folder that are 14 days or older
and have an extension of ".BAK"
SELECT dbo.DeleteFiles('C:\Backups', 14, '.BAK') AS FilesDeleted
In this example we are deleting files in the "C:\Backups" folder that are 7 days or older
and have an extension of ".trn"
SELECT dbo.DeleteFiles('C:\Backups', 7, '.trn') AS FilesDeleted
In this example we are deleting files in the "C:\Backups" folder that are 14 days or older
and have an extension of ".LOG"
SELECT dbo.DeleteFiles('C:\Backups', 14, '.LOG') AS FilesDeleted

Step 5 - Cleanup
To get rid of the code you will need to delete the DLL that is created from the compile
step as well as the VB file that was created.
In addition, run this T-SQL code to drop the objects that were created.
DROP FUNCTION dbo.DeleteFiles
GO
DROP ASSEMBLY CLRFunctions
GO

Summary
That's all there is to creating a CLR function to delete older backup files. This function as
built only looks in one directory as well as only deals with one type of file extension at a
time, so these are some things that could be done to improve this code.
One thing to note is that when the files are deleted they are not put into the recycle bin,
so make sure you test this in a test environment to make sure you understand what is
occurring before you implement this on your production servers.
Next Steps
Give this example a try and see what other functions you could write that could
take advantage of the CLR
IF you have some enhancements to this function that you would like to share,
please post them in this forumhttp://blogs.mssqltips.com/forums/t/65.aspx
If you have CLR functions that you want to share with the rest of the
MSSQLTips.com community, please send them to tips@mssqltips.com so we can
post them for others to use or post them in the forums.
If you don't know how to write either VB or C# now is the time to begin learning.


Using the FORFILES Command to Delete SQL Server Backups
Using the FORFILES Command to Delete
SQL Server Backups

By: Tim Ford | Read Comments (8) | Related Tips: More > Backup
Problem
Recently I constructed a new backup process that I want to institute globally across all
my SQL Server 2005 instances. This backup process will not only backup all the
databases I point it towards, but at the same time will script out the backup commands
to a single file in the format of F_YYYYMMDD.sql if the backup process is a full database
backup or D|T_YYMMDD_HHMMSS.sql if the backup process is a differential (D) or
transaction log (T) backup. These script files are then stored in a subfolder under the
backup directory on the SQL Server. The process works great, but I only don't want to
keep every .sql file. I cant see the need to keep these scripts after 30 days. Is there a
way I can automate a file deletion process from within SQL Server?
Solution
While there are many ways the file deletion process can be handled with T-SQL code. I
use the xp_cmdshell command along with the FORFILES command for a very similar
process to what you have outlined. Solid information of FORFILES is available
from Microsoft TechNet, but I will touch on much of the structure and use of FORFILES
for your purposes in this tip.
The FORFILES command will select a subset of files and execute a command against the
set. The command requires the following parameters and accepts the following
variables:
Parameters
Parameter Name Description
/p Path
/m Search Mask (default is *.*)
/s Subdirectories will be searched recursively if this parameter is included
/c <command>
Command to be executed against each file in the result set, commands must
be enclosed in double-quotes, default is "cmd c/ echo @file"
/d
Date range for file selection, using Last Modified Date as the criterion for the
file. When the /d parameter is in the form of MM/DD/YYYY, file meeting the
criteria of +/- the specified date are included. When in the format of a smallint
(-32,768 - 32,768) the files +/- the files with a modified date +/- that number of
days from the current date are included in the file result set.
Variables
Variable Name Description
@FILE File name
@FNAME File name without extension
@EXT File extension
@PATH Full path of the file
@RELPATH Relative path of the file
@ISDIR Evaluates as TRUE if the file type is a directory
@FSIZE File size in bytes
@FDATE Last modified date stamp on the file
@FTIME Last modified timestamp on the file
Using these parameters the following examples could be constructed to take care of your
dilemma for deleting your backup script files. You can create scripts based upon
modification date/time or backup type. You can even construct scripts that utilize both
criteria. We will now take a closer look at these potential scripts. Remember that you
will be executing these from within T-SQL code, so you will need to wrap the statements
within an xp_cmdshell call in the format
of EXEC xp_cmdshell 'FORFILES COMMAND'. Please note that in all examples I am using
the /Q and /F flags for the del command. These signify that the command will use quiet
mode (/Q) and will even delete read-only files (/F).
Examples
Delete all .sql files in the C:\Backup directory and its subfolders where the file modified
date is older than 10/18/2008.
EXEC xp_cmdshell 'FORFILES /p c:\BACKUP /s /m *.sql /d 10/18/2008 /c "CMD /C del /Q /F @FIL
E"'
Delete all .sql files in the C:\Backup directory and its subfolders where the file modified
date is more than 30 days old.
EXEC xp_cmdshell 'FORFILES /p c:\BACKUP /s /m *.sql /d -30 /c "CMD /C del /Q /F @FILE"'
Delete all .sql files in the C:\Backup directory and its subfolders where the file modified
date is more than 30 days old and the file name starts with an "F_".
EXEC xp_cmdshell 'FORFILES /p c:\BACKUP /s /m F_*.sql /d -30 /c "CMD /C del /Q /F @FILE"'
Next Steps
Modify the code above to fit your retention policy, file structure and needs.
Add the modified code to a subsequent job step in the SQL Agent job that runs
your backup process. Includeverbose SQL Agent job logging to verify that the
process is working correctly.
Keep in mind that the FORFILES command does a lot more than just deleting
files. As an example, it can be used to list files for other processes as well.
Review other file deletion automation tips from MSSQLTips.com.
Review tips on xp_cmdshell at MSSQLTips.com

Automating SQL Server 2005 Express Backups and Deletion of Older Backup Files
Automate SQL Server Express Backups and
Deletion of Older Backup Files

By: Edwin Sarmiento | Read Comments (34) | Related
Tips: More > Express Edition
Problem
As a lot of line-of-business applications are being built with SQL Server 2005 Express
Edition as their backend database, we need to make sure that we backup the system
and the user databases running on these instances. Unfortunately, SQL Server 2005
Express Edition does not come with SQL Agent which we would normally use to create a
database maintenance plan to backup all the databases. How do we perform a backup of
our system and user databases in SQL Server 2005 Express Edition similar to how we do
it in other editions?
Solution
We can use a combination of VBScript and TSQL with Task Manager in Windows to
automate the creation of user and system database backups in SQL Server 2005 Express
Edition.
Note: All files should be saved in folder E:\SQL_Backup\scripts. This can be changed,
but this example is setup for this folder. If you save to a different folder you will need to
update the scripts accordingly.
Step 1 - Create the TSQL script
The TSQL script below generates a database backup similar to the formatting generated
by the database maintenance plan, taking into account the date and time the backup
files were generated. We save the script as a .sql file,
E:\SQL_Backup\scripts\backupDB.sql, which we will call from a batch file using sqlcmd.
DECLARE @dateString CHAR(12), @dayStr CHAR(2), @monthStr CHAR(2), @hourStr CHAR(2),
@minStr CHAR(2)
--month variable
IF (SELECT LEN(CAST(MONTH(GETDATE()) AS CHAR(2))))=2
SET @monthSTR=CAST(MONTH(GETDATE()) AS CHAR(2))
ELSE
SET @monthSTR= '0' + CAST(MONTH(GETDATE()) AS CHAR(2))
--day variable
IF (SELECT LEN(CAST(DAY(GETDATE()) AS CHAR(2))))=2
SET @daySTR=CAST(DAY(GETDATE()) AS CHAR(2))
ELSE
SET @daySTR='0' + CAST(DAY(GETDATE()) AS CHAR(2))
--hour variable
IF (SELECT LEN(DATEPART(hh, GETDATE())))=2
SET @hourStr=CAST(DATEPART(hh, GETDATE()) AS CHAR(2))
ELSE
SET @hourStr= '0' + CAST(DATEPART(hh, GETDATE()) AS CHAR(2))
--minute variable
IF (SELECT LEN(DATEPART(mi, GETDATE())))=2
SET @minStr=CAST(DATEPART(mi, GETDATE()) AS CHAR(2))
ELSE
SET @minStr= '0' + CAST(DATEPART(mi, GETDATE()) AS CHAR(2))
--name variable based on time stamp
SET @dateString=CAST(YEAR(GETDATE()) AS CHAR(4)) + @monthStr + @dayStr + @hourStr +
@minStr
--=================================================================
DECLARE @IDENT INT, @sql VARCHAR(1000), @DBNAME VARCHAR(200)
SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND NAME
NOT IN ('TEMPDB')
WHILE @IDENT IS NOT NULL
BEGIN
SELECT @DBNAME = NAME FROM SYS.DATABASES WHERE database_id = @IDENT
/*Change disk location here as required*/
SELECT @SQL = 'BACKUP DATABASE '+@DBNAME+' TO DISK = ''E:\SQL_Backup\'+@DBNAME+'
_db_' + @dateString +'.BAK'' WITH INIT'
EXEC (@SQL)
SELECT @IDENT=MIN(database_id) FROM SYS.DATABASES WHERE [database_id] > 0 AND da
tabase_id>@IDENT AND NAME NOT IN ('TEMPDB')
END

Step 2 - Create the VBScript file
Next, we will need to create a VBScript file which will be responsible for cleaning up old
copies of the database backups. The script also writes to a log file which records the
database backup files.
You do need to create an empty file named E:\SQL_Backup\scripts\LOG.txt to
save a log of the deleted files.
Also copy the below script and save as E:\SQL_Backup\scripts\deleteBAK.vbs
On Error Resume Next
Dim fso, folder, files, sFolder, sFolderTarget
Set fso = CreateObject("Scripting.FileSystemObject")

'location of the database backup files
sFolder = "E:\SQL_Backup\"

Set folder = fso.GetFolder(sFolder)
Set files = folder.Files

'used for writing to textfile - generate report on database backups deleted
Const ForAppending = 8

'you need to create a folder named scripts for ease of file management &
'a file inside it named LOG.txt for delete activity logging
Set objFile = fso.OpenTextFile(sFolder & "\scripts\LOG.txt", ForAppending)

objFile.Write "================================================================" &
VBCRLF & VBCRLF
objFile.Write " DATABASE BACKUP FILE REPORT " &
VBCRLF
objFile.Write " DATE: " & FormatDateTime(Now(),1) & "" &
VBCRLF
objFile.Write " TIME: " & FormatDateTime(Now(),3) & "" &
VBCRLF & VBCRLF
objFile.Write "================================================================" &
VBCRLF

'iterate thru each of the files in the database backup folder
For Each itemFiles In files
'retrieve complete path of file for the DeleteFile method and to extract
'file extension using the GetExtensionName method
a=sFolder & itemFiles.Name

'retrieve file extension
b = fso.GetExtensionName(a)
'check if the file extension is BAK
If uCase(b)="BAK" Then

'check if the database backups are older than 3 days
If DateDiff("d",itemFiles.DateCreated,Now()) >= 3 Then

'Delete any old BACKUP files to cleanup folder
fso.DeleteFile a
objFile.WriteLine "BACKUP FILE DELETED: " & a
End If
End If
Next

objFile.WriteLine "================================================================
" & VBCRLF & VBCRLF

objFile.Close

Set objFile = Nothing
Set fso = Nothing
Set folder = Nothing
Set files = Nothing

Step 3 - Create the batch file that will call the TSQL script and the VBScript file
We need to create the batch file which will call both the TSQL script and the VBScript
file. The contents of the batch file will be a simple call to the sqlcmd.exe and a call to the
VBScript file using either wscript.exe or simply calling the file. Save the file as
E:\SQL_Backup\scripts\databaseBackup.cmd and save it in the scripts subfolder
REM Run TSQL Script to backup databases
sqlcmd -S<INSTANCENAME>-E -i"E:\SQL_Backup\scripts\backupDB.sql"
REM Run database backup cleanup script
E:\SQL_Backup\scripts\deleteBAK.vbs

Step 4 - Create a task in Windows Task Scheduler
Create a daily task in Windows Task Scheduler that will call the batch file created in the
previous step. This can be found in the Control Panel -> Scheduled Tasks or under Start
-> All Programs -> Accessories -> System Tools -> Scheduled Tasks.
Since we are using Windows authentication to run the TSQL script, use a Windows
account that is a member of the db_backupoperator role of all the databases
Launch "Scheduled Tasks"
Click on Add Scheduled Task
Browse to the "E:\SQL_Backup\scripts" folder and select databaseBackup.cmd
Pick the frequency and time for the backups to run
Lastly, enter a Windows account that has at least db_backupoperator role
privileges for all of the databases
See screenshots below




Next Steps
Implement this solution on your SQL Server 2

Rename Files - Since we are talking about files, in many of the scripts I have written I have renamed
files so it is easy to determine that they have been processed. At the most simple level, the rename
command can be called with the current directory and file name followed by the new file name.


Create Directories - In the example code below, we are creating a new directory based on the
current date with the mkdir DOS command.
-- 1 - Declare variables
DECLARE @CMD1 varchar(8000)
DECLARE @RestoreRootDirectory varchar(255)
DECLARE @CurrentDate datetime
DECLARE @CurrentName varchar(8)
-- 2 - Initialize variables
SET @CMD1 = ''
SET @RestoreRootDirectory = 'C:\Temp\'
SET @CurrentDate = GETDATE()
SELECT @CurrentName = CONVERT(varchar(8), @CurrentDate, 112)
-- 3a - Create the current directory
SELECT @CMD1 = 'EXEC master.dbo.xp_cmdshell ' + char(39) + 'mkdir
' + @RestoreRootDirectory +@CurrentName + '\' + char(39)
-- SELECT @CMD1
EXEC(@CMD1)
-- 3b - Test the error value
IF @@ERROR <> 0
BEGIN
RAISERROR ('3a - Restore directory not created', 16, 1)
RETURN
END

Remove Directories - In the example code below, we are removing a directory based on the the
current date minus one.
-- 1 - Declare variables
DECLARE @CMD1 varchar(8000)
DECLARE @RestoreRootDirectory varchar(255)
DECLARE @CurrentDate datetime
DECLARE @PreviousName varchar(8)
-- 2 - Initialize variables
SET @CMD1 = ''
SET @RestoreRootDirectory = 'C:\Temp\'
SET @CurrentDate = GETDATE()
SELECT @PreviousName = CONVERT(varchar(8), @CurrentDate-1, 112)
-- 3a - Drop the previous directory
SELECT @CMD1 = 'EXEC master.dbo.xp_cmdshell ' + char(39) + 'rmdir
' + @RestoreRootDirectory +@PreviousName + '\ /q' + char(39)
-- SELECT @CMD1
EXEC(@CMD1)
-- 3b - Test the error value
IF @@ERROR <> 0
BEGIN
RAISERROR ('3a - Restore directory not deleted', 16, 1)
RETURN
END



Troubleshooting and Research
DOS Troubleshooting and Research Commands
Gather system information - Winmsd can be invoked directly from the Start | Run command by
typing in WINMSD. With this command you are able to get a basic set of information about the
machine.


Validating a machine is online after a reboot - Although the ping command will not tell you when
your application is operational after a reboot, it will let you know when Windows should be operational
so you can begin to validate SQL Server has recovered and the application is operational.


Active Ports - The netstat -a command is valuable to provide the active TCP connections with the
TCP and UDP ports the SQL Server is listening on.


Network Cards - Another command for general troubleshooting is the ipconfig command. In this
example we are listing all of the information across each of the NICs, but this command does offer
more options in terms of flushing DNS, releasing DNS, renewing DNS, etc.


Free disk space - The master..xp_fixeddrives extended stored procedure lists the free space in MB
per disk drive. One situation I have run into with processes requiring a significant amount of disk
space on a monthly basis is to check the free disk space prior to running the remainder of the
code. It is frustrating to have a process run for an extended period of time only to find out sufficient
disk space was not available in the first place. Check out the Determine Free Disk Space in SQL
Server with T-SQL Code tip for additional information.
EXEC master.sys.xp_fixeddrives
GO

Directory structure - The master..xp_subdirs extended stored procedure provides the ability to
capture the sub directories.
EXEC master.sys.xp_subdirs 'c:\'
GO

Next Steps
As you are faced with more situations where you need to access the Windows file
system, be sure to see what options are available with extended stored
procedures, DOS and PowerShell.
As your organization has time, be sure to check out PowerShell to see how this
new product can improve your overall infrastructure management.
For more information about master..xp_cmdshell visit:
o Enabling xp_cmdshell in SQL Server 2005
o Where is the Surface Area Configuration tool in SQL Server 2008
For more information about PowerSheel visit:
o Introduction to Windows PowerShell for the SQL Server DBA Part 1
o Introduction to Windows PowerShell for the SQL Server DBA Part 2
o PowerShell Support in SQL Server 2008 - Invoke-Sqlcmd Cmdlet

Potrebbero piacerti anche