现在的位置: 首页 > 综合 > 正文

取硬盘大小及可用空间

2012年10月13日 ⁄ 综合 ⁄ 共 1823字 ⁄ 字号 评论关闭

参考: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

 

抱歉!评论已关闭.