posts - 83, comments - 88, trackbacks - 0, articles - 1
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

公告

取硬盘大小及可用空间

Posted on 2011-07-28 16:09 nzperfect 阅读(158) 评论(2) 编辑 收藏

参考:http://www.mssqltips.com/tip.asp?tip=2444

取硬盘大小及可用空间

declare @svrName varchar(255)
declare @sql varchar(400)
--by default it will take the current server name, we can the set the server name as well
set @svrName = case charindex('\',@@servernamewhen 0 then @@servername else 
left(@@servername,charindex('\',@@servername)-1end
set @sql = 'powershell.exe -c "Get-WmiObject -ComputerName ' + QUOTENAME(@svrName,''''+ ' -Class Win32_Volume -Filter ''DriveType = 3'' | select name,capacity,freespace | foreach{$_.name+''|''+$_.capacity/1048576+''%''+$_.freespace/1048576+''*''}"'
--creating a temporary table
print(@sql)
CREATE TABLE #output
(line 
varchar(255))
--inserting disk name, total space and free space value in to temporary table
insert #output
EXEC xp_cmdshell @sql
--script to retrieve the values in MB from PS Script output
select rtrim(ltrim(SUBSTRING(line,1,CHARINDEX('|',line) -1))) as drivename
      ,
round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('|',line)+1,
      (
CHARINDEX('%',line) -1)-CHARINDEX('|',line)) )) as Float),0as 'capacity(MB)'
      ,
round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('%',line)+1,
      (
CHARINDEX('*',line) -1)-CHARINDEX('%',line)) )) as Float),0as 'freespace(MB)'
from #output
where line like '[A-Z][:]%'
order by drivename
--script to retrieve the values in GB from PS Script output
select rtrim(ltrim(SUBSTRING(line,1,CHARINDEX('|',line) -1))) as drivename
      ,
round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('|',line)+1,
      (
CHARINDEX('%',line) -1)-CHARINDEX('|',line)) )) as Float)/1024,0as 'capacity(GB)'
      ,
round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('%',line)+1,
      (
CHARINDEX('*',line) -1)-CHARINDEX('%',line)) )) as Float/1024 ,0)as 'freespace(GB)'
from #output
where line like '[A-Z][:]%'
order by drivename
--script to drop the temporary table
drop table #output