Sunday, August 27, 2017

Read windows drives info without SysAdmin permssion


if  @@microsoftversion / power(2, 24) >= 9
begin

declare @oleautomationprocedures bit
declare @isshowadvancedoptions bit


select @isshowadvancedoptions = convert(int, isnull(value, value_in_use))
from  sys.configurations
where  name = 'show advanced options'
if @isshowadvancedoptions = 0
begin
exec sp_configure 'show advanced options', 1;
reconfigure;
end


select @oleautomationprocedures = convert(int, isnull(value, value_in_use))
from  sys.configurations
where  name = 'ole automation procedures' ;
if @oleautomationprocedures = 0
begin
exec sp_configure 'ole automation procedures', 1;
reconfigure;
end

end

set nocount on
declare @hr int;
declare @fso int;
declare @driveletter char(1);
declare @odrive int;
declare @totalsize varchar(20);
declare @volumename nvarchar(256);
declare @mb numeric;
set @mb = 1048576;
set @driveletter = '';

if object_id('tempdb..#fixeddrives') is not null
drop table #fixeddrives;

create table #fixeddrives (
[Drive] varchar(10) primary key,
[Drive Label] nvarchar(256),
[Total Capacity MB] numeric(10,2),
[Space Used MB] numeric(10,2),
[Free Space MB] numeric(10,2),
[% Free] numeric(10,2)
);

insert into #fixeddrives([Drive], [Free Space MB])
exec master..xp_fixeddrives;

exec @hr=sp_OACreate 'scripting.filesystemobject',@fso out
if @hr <> 0 exec sp_oageterrorinfo @fso

while exists (select 1 from #fixeddrives d where d.Drive > @driveletter)
begin
select top 1 @driveletter = d.Drive
from #fixeddrives d
where d.Drive > @driveletter
order by d.Drive asc

exec @hr = sp_OAMethod @fso,'getdrive', @odrive out, @driveletter;
if @hr <> 0 exec sp_oageterrorinfo @fso;

exec @hr = sp_OAGetProperty @odrive,'totalsize', @totalsize out;
if @hr <> 0 exec sp_oageterrorinfo @odrive;

exec @hr = sp_OAGetProperty @odrive,'volumename', @volumename out;
if @hr <> 0 exec sp_oageterrorinfo @fso;

update #fixeddrives
set [Total Capacity MB]= @totalsize/@mb ,
[Drive Label]= @volumename
where
Drive = @driveletter;

end

exec @hr=sp_OADestroy @fso;

if @hr <> 0
exec sp_oageterrorinfo @fso;

update #fixeddrives
set [Space Used MB]= [Total Capacity MB] - [Free Space MB],
[% Free] = [Free Space MB]* 100/[Total Capacity MB];

select [Drive]
, [Drive Label]
, [Total Capacity MB]
, [Space Used MB]
, [Free Space MB]
, [% Free]
from #fixeddrives


if  @@microsoftversion / power(2, 24) >= 9
begin
if (select convert(int, isnull(value, value_in_use)) from sys.configurations
where  name = 'ole automation procedures') <> @oleautomationprocedures
begin
exec sp_configure 'ole automation procedures', @oleautomationprocedures;
reconfigure;
end

if (select convert(int, isnull(value, value_in_use)) from sys.configurations
where  name = 'show advanced options') <> @isshowadvancedoptions
begin
exec sp_configure 'show advanced options', @isshowadvancedoptions
reconfigure with override
end

end

No comments:

Post a Comment