GeorgeLittle
(Fresh Scripter)
2013-10-31 02:53 PM
Get size of all users My Documents and Desktops to text file

Hi

So after a while of playing with powershell I am after a kix script that can be run from local machines to do the following;

Find the current logged on user
Find the size of my document and desktop folders for all users

record all this infomation in a text file on a network share or a mdb

I have done this using powershell but its so slow and half the machines dont have powershell on them due to age

Cheers again guys


ShaneEP
(MM club member)
2013-10-31 04:29 PM
Re: Get size of all users My Documents and Desktops to text file

The current logged on user is simply @UserID

As far as the folder sizes, do you mean the size of each user profile thats on the machine, or the actual 'All Users' profile?


ShaneEP
(MM club member)
2013-10-31 04:44 PM
Re: Get size of all users My Documents and Desktops to text file

Here is how I would go about it. There may be an easier way to get the profile list or folder size, but these are the methods that first pop into my head.

Just change the first line to point to whatever text file you want it to be saved in.
(Warning, it overwrites existing data, so make sure you dont point to a file thats important.)

 Code:
$logFile = @ScriptDir+"\Profile Sizes.txt"

$userDir = "%USERPROFILE%"
$profilesDir = SubStr($userDir, 1, InStrRev($userDir, "\"))
$profiles = DirList($profilesDir, 3)

$nul = RedirectOutput($logFile, 1)

For Each $profile in $profiles
   If Right($profile, 1) = "\"
      ? $profile
      ? "--------------------"
      ? "Desktop Size:   "+FormatNumber(fnGetFolderProp($profile+"Desktop","Size"), 0)
      ? "Documents Size: "+FormatNumber(fnGetFolderProp($profile+"My Documents","Size"), 0)
      ? ?
   Endif
Next

$nul = RedirectOutput("")


Function fnGetFolderProp($sFldr,$sProp)
    Dim $objFSO, $objFldr, $nul
    $objFSO = CreateObject("Scripting.FileSystemObject")
    If Not VarType($objFSO)=9 Exit 1 EndIf
    $objFldr = $objFSO.GetFolder($sFldr)
    If Not VarType($objFldr)=9 Exit 3 EndIf
    $nul=Execute("$$fnGetFolderProp = $$objFldr."+$sProp)
    If VarType($fnGetFolderProp)=0 Exit 87 EndIf
EndFunction

Function dirlist($dirname, optional $options)
  dim $filename, $counter, $filepath, $mask
  dim $list, $sublist, $subcounter
  $counter=-1
  $dirname=trim($dirname)
  if $dirname=''
    $dirname=@CURDIR
  endif
  if right($dirname,1)='\'
    $dirname=left($dirname,len($dirname)-1)
  endif
  if getfileattr($dirname) & 16
    $mask='*.*'
  else
    $mask=substr($dirname,instrrev($dirname,'\')+1)
    $dirname=left($dirname,len($dirname)-len($mask)-1)
  endif
  redim $list[10]
  $filename=dir($dirname+'\'+$mask)
  while $filename<>'' and @ERROR=0
    if $filename<>'.' and $filename<>'..'
      select
      case (getfileattr($dirname+'\'+$filename) & 16)
        if $options & 1
          $counter=$counter+1
          if $options & 2
            $list[$counter]=$dirname+'\'+$filename+'\'
          else
            $list[$counter]=$filename+'\'
          endif
        endif
        if ($options & 4)
          $sublist=dirlist($dirname+'\'+$filename+'\'+$mask,$options)
          if ubound($sublist)+1
            redim preserve $list[ubound($list)+ubound($sublist)+1]
            for $subcounter=0 to ubound($sublist)
              $counter=$counter+1
              if $options & 2
                $list[$counter]=$dirname+'\'+$filename+'\'+$sublist[$subcounter]
              else
                $list[$counter]=$filename+'\'+$sublist[$subcounter]
              endif
            next
          endif
        endif
      case ($options & 2)
        $counter=$counter+1
        $list[$counter]=$dirname+'\'+$filename
      case 1
        $counter=$counter+1
        $list[$counter]=$filename
      endselect
      if $counter mod 10
        redim preserve $list[$counter+10]
      endif
    endif
    $filename = dir('')
  loop
  if $counter+1
    redim preserve $list[$counter]
  else
    $list=''
  endif
  if $mask<>'*.*' and ($options & 4)
    $filename=dir($dirname+'\*.*')
    while $filename<>'' and @ERROR=0
      if $filename<>'.' and $filename<>'..'
        if (getfileattr($dirname+'\'+$filename) & 16)
          $sublist=dirlist($dirname+'\'+$filename+'\'+$mask,4)
          if ubound($sublist)+1
            redim preserve $list[ubound($list)+ubound($sublist)+1]
            for $subcounter=0 to ubound($sublist)
              $counter=$counter+1
              if $options & 2
                $list[$counter]=$dirname+'\'+$filename+'\'+$sublist[$subcounter]
              else
                $list[$counter]=$filename+'\'+$sublist[$subcounter]
              endif
            next
          endif
        endif
      endif
      $filename = dir('')
    loop
  endif
  if $counter+1
    redim preserve $list[$counter]
  else
    $list=''
  endif
  $dirlist=$list
endfunction


GeorgeLittle
(Fresh Scripter)
2013-10-31 04:54 PM
Re: Get size of all users My Documents and Desktops to text file

Thats really cool Shane EP thanks and runs in half the time powershell does

So my current plan would be to deploy this to all the machines. However would it be possible to run it against unc paths ? Just thinking out loud .


ShaneEP
(MM club member)
2013-10-31 06:33 PM
Re: Get size of all users My Documents and Desktops to text file

You should be able to to deploy to all machines, and it should work with UNCs as far as I know.

However, the way it runs now, it would overwrite the log file every time it was run from a client. There are a couple options to get around that. Use an INI file instead of a txt file and create a new section in the INI for every workstation that it runs from. Or you could create a different txt file for each machine that it runs from.


ShaneEP
(MM club member)
2013-10-31 08:22 PM
Re: Get size of all users My Documents and Desktops to text file

Here is an example of how to log the info to an INI file.

It creates a new section in the file for each Workstation\Account.

 Code:
$logFile = @ScriptDir+"\Profile Sizes.ini"

$profiles = DirList(SubStr("%USERPROFILE%", 1, InStrRev("%USERPROFILE%", "\")), 3)

For Each $profile in $profiles
   If Right($profile, 1) = "\"
      $profilename = Split($profile, "\")
      $profilename = $profilename[UBound($profilename)-1]
      $nul = WriteProfileString($logfile, @WkSta+"\"+$profilename, "Desktop", fnGetFolderProp($profile+"Desktop","Size"))
      $nul = WriteProfileString($logfile, @WkSta+"\"+$profilename, "Documents", fnGetFolderProp($profile+"My Documents","Size"))
   Endif
Next




Function fnGetFolderProp($sFldr,$sProp)
    Dim $objFSO, $objFldr, $nul
    $objFSO = CreateObject("Scripting.FileSystemObject")
    If Not VarType($objFSO)=9 Exit 1 EndIf
    $objFldr = $objFSO.GetFolder($sFldr)
    If Not VarType($objFldr)=9 Exit 3 EndIf
    $nul=Execute("$$fnGetFolderProp = $$objFldr."+$sProp)
    If VarType($fnGetFolderProp)=0 Exit 87 EndIf
EndFunction

Function dirlist($dirname, optional $options)
  dim $filename, $counter, $filepath, $mask
  dim $list, $sublist, $subcounter
  $counter=-1
  $dirname=trim($dirname)
  if $dirname=''
    $dirname=@CURDIR
  endif
  if right($dirname,1)='\'
    $dirname=left($dirname,len($dirname)-1)
  endif
  if getfileattr($dirname) & 16
    $mask='*.*'
  else
    $mask=substr($dirname,instrrev($dirname,'\')+1)
    $dirname=left($dirname,len($dirname)-len($mask)-1)
  endif
  redim $list[10]
  $filename=dir($dirname+'\'+$mask)
  while $filename<>'' and @ERROR=0
    if $filename<>'.' and $filename<>'..'
      select
      case (getfileattr($dirname+'\'+$filename) & 16)
        if $options & 1
          $counter=$counter+1
          if $options & 2
            $list[$counter]=$dirname+'\'+$filename+'\'
          else
            $list[$counter]=$filename+'\'
          endif
        endif
        if ($options & 4)
          $sublist=dirlist($dirname+'\'+$filename+'\'+$mask,$options)
          if ubound($sublist)+1
            redim preserve $list[ubound($list)+ubound($sublist)+1]
            for $subcounter=0 to ubound($sublist)
              $counter=$counter+1
              if $options & 2
                $list[$counter]=$dirname+'\'+$filename+'\'+$sublist[$subcounter]
              else
                $list[$counter]=$filename+'\'+$sublist[$subcounter]
              endif
            next
          endif
        endif
      case ($options & 2)
        $counter=$counter+1
        $list[$counter]=$dirname+'\'+$filename
      case 1
        $counter=$counter+1
        $list[$counter]=$filename
      endselect
      if $counter mod 10
        redim preserve $list[$counter+10]
      endif
    endif
    $filename = dir('')
  loop
  if $counter+1
    redim preserve $list[$counter]
  else
    $list=''
  endif
  if $mask<>'*.*' and ($options & 4)
    $filename=dir($dirname+'\*.*')
    while $filename<>'' and @ERROR=0
      if $filename<>'.' and $filename<>'..'
        if (getfileattr($dirname+'\'+$filename) & 16)
          $sublist=dirlist($dirname+'\'+$filename+'\'+$mask,4)
          if ubound($sublist)+1
            redim preserve $list[ubound($list)+ubound($sublist)+1]
            for $subcounter=0 to ubound($sublist)
              $counter=$counter+1
              if $options & 2
                $list[$counter]=$dirname+'\'+$filename+'\'+$sublist[$subcounter]
              else
                $list[$counter]=$filename+'\'+$sublist[$subcounter]
              endif
            next
          endif
        endif
      endif
      $filename = dir('')
    loop
  endif
  if $counter+1
    redim preserve $list[$counter]
  else
    $list=''
  endif
  $dirlist=$list
endfunction


GeorgeLittle
(Fresh Scripter)
2013-10-31 09:50 PM
Re: Get size of all users My Documents and Desktops to text file

Cheers shane

can you give me one bit more assistance and show me how I might do it using a list of computer unc paths ?

eg if the text file had

\\computer1\c$\documents and settings\
\\computer2\c$\documents and settings\
\\computer3\c$\documents and settings\

I think that I could load the file using Glens FILOio udf


Mart
(KiX Supporter)
2013-11-01 08:47 AM
Re: Get size of all users My Documents and Desktops to text file

You could load the entire file into memory and then process it line by line or you can do it like shown below. It all depends on where the file is located, how big it is, your personal preferences, etc...

 Code:
Break on

$rc = Open(1, "c:\Somefile.txt", 2)
$line = ReadLine(1)

While Not @ERROR And $line <> ""
		
	;do stuff here
	
	$line = ReadLine(1)
Loop

Close(1)


Glenn BarnasAdministrator
(KiX Supporter)
2013-11-01 01:30 PM
Re: Get size of all users My Documents and Desktops to text file

Using FileIO():
 Code:
$aTargets = FileIO('.\Filename.txt', 'R')
For Each $Host in $aTargets
  ; run code to query each $Host value
  If Ping($Host)
    $HostPath = '\\' + $Host + 'C$\path_to_query'
    'Processing ' $HostPath ? ; for debugging or status reporting

    ; run any necessary command using $HostPath to reference the target path

  EndIf
Next
Also, the file should be a list of hostnames only - no paths or slashes since that never changes. This is illustrated above. It allows you to use the Ping UDF to make sure the system is alive before attempting to make queries.

Glenn


GeorgeLittle
(Fresh Scripter)
2013-11-01 04:53 PM
Re: Get size of all users My Documents and Desktops to text file

so heres my go at it still not working

 Code:
$aTargets = FileIO('c:\scripts\hosts.txt', 'R')
For Each $Host in $aTargets
  ; run code to query each $Host value
  If Ping($Host)
    $HostPath = '\\' + $Host + 'C$\users'
    'Processing ' $HostPath ? ; for debugging or status reporting

    ; run any necessary command using $HostPath to reference the target path
$logFile = @ScriptDir+"\Profile Sizes.ini"

$profiles = DirList($HostPath)

For Each $profile in $profiles
   If Right($profile, 1) = "\"
      $profilename = Split($profile, "\")
      $profilename = $profilename[UBound($profilename)-1]
      $nul = WriteProfileString($logfile, @WkSta+"\"+$profilename, "Desktop", fnGetFolderProp($profile+"Desktop","Size"))
      $nul = WriteProfileString($logfile, @WkSta+"\"+$profilename, "Documents", fnGetFolderProp($profile+"My Documents","Size"))
   Endif
Next




Function fnGetFolderProp($sFldr,$sProp)
    Dim $objFSO, $objFldr, $nul
    $objFSO = CreateObject("Scripting.FileSystemObject")
    If Not VarType($objFSO)=9 Exit 1 EndIf
    $objFldr = $objFSO.GetFolder($sFldr)
    If Not VarType($objFldr)=9 Exit 3 EndIf
    $nul=Execute("$$fnGetFolderProp = $$objFldr."+$sProp)
    If VarType($fnGetFolderProp)=0 Exit 87 EndIf
EndFunction

Function dirlist($dirname, optional $options)
  dim $filename, $counter, $filepath, $mask
  dim $list, $sublist, $subcounter
  $counter=-1
  $dirname=trim($dirname)
  if $dirname=''
    $dirname=@CURDIR
  endif
  if right($dirname,1)='\'
    $dirname=left($dirname,len($dirname)-1)
  endif

  EndIf
Next
;FUNCTION         Ping()
;
;AUTHOR           Jochen Polster (jochenDOTpolsterATgmxDOTnet)
;
;VERSION HISTORY  1.0 - 11/24/2001 Initial Release
;                 1.1 - 11/11/2004 Fixed problems regarding spaces in folder names
;                                  of script directory (thanks to Alistair)
;                 1.2 - 12/07/2004 Fixed for NoVarsInStrings and Explicit on
;
;ACTION           Pings the Computer specified, or returns its ip address (Wins Resolved)
;
;SYNTAX           Ping(Computer,GetIP,[LoopCount],[Timeout])
;
;PARAMETERS       Computer (Required)
;                  -  String value representing the Computer to ping
;
;                 GetIp (Required)
;                  -  If specified (1), the function will return the ip-address
;                     of specified Computer rather than pinging it ...
;                     Has to be 0 if you want to check for reply !
;
;                 LoopCount (Optional but useful !)
;                  -  Integer value representing the number of times
;                     the Computer shall be pinged
;
;                 Timeout (Optional)
;                  -  if ommited the Computer gets pinged with the default
;                     timeout (1s) and default retries (4)
;
;REMARKS          If there is a reply the function will return immediately with 1
;                 so it could be faster not specifiying a timeout.
;
;RETURNS          0 - No reply
;                 1 - Ping reply
;                 Optional - ip address of specified Computer
;
;DEPENDENCIES     None
;
;EXAMPLES         call "path\Ping.udf"
;                 if Ping("www.microsoft.com",0,12,5000) ;pings for max. 60 seconds
;                 	run "%ComSpec% /c start www.microsoft.com"
;                 else
;                 	'Site isn't available ' ?
;                 endif
;                 if Ping("www.microsoft.com",0,15) ;pings also for max. 60 seconds
;                 	run "%ComSpec% /c start www.microsoft.com"
;                 else
;                 	'Site isn't available ' ?
;                 endif
;                 $ip = Ping("www.microsoft.com",1)
;                 $ip ?

function Ping($Computer,$GetIP,optional $LoopCount,optional $TimeOut)
	if $GetIP
		dim $ip, $ipfile, $
		$ipfile = @scriptdir + '\ip.txt'
		shell '%Comspec% /q /e:1024 /c for /F "tokens=2 delims=[]" %%i IN ('+ chr(39)
		+ '"ping ' + $Computer + ' -n 1 | find "]""' + chr(39) + ') do echo %%i >"' + $ipfile + '"'
		$ = open(10,$ipfile,2) $ip = readline(10) $ = close(10) del $ipfile
		if $ip
			$Ping = $ip
		else
			$Ping = 'Bad IP address ' + $Computer + '!'
		endif
		exit 0
	else
		if $TimeOut
			for $c = 0 to $LoopCount
				shell '%Comspec% /C ping ' + $Computer + ' -n 1 -w ' + $TimeOut + ' | find /C "TTL=" > nul'
				if @error = 0
					$Ping = 1
					exit 0
				endif
			next
		else
			for $c = 0 to $LoopCount
				shell '%Comspec% /C ping ' + $Computer + ' | find /C "TTL=" > nul'
				if @error = 0
					$Ping = 1
					exit 0
				endif
			next
		endif
		$Ping = 0
	endif
endfunction




ShaneEP
(MM club member)
2013-11-01 05:58 PM
Re: Get size of all users My Documents and Desktops to text file

Make sure to add the FileIO() Function.

ShaneEP
(MM club member)
2013-11-01 06:00 PM
Re: Get size of all users My Documents and Desktops to text file

Also if you're querying it remotely, you won't want to use @WkSta+"\"+$profilename as the entry name.

Probably something more like $Host+"\"+$profilename


ShaneEP
(MM club member)
2013-11-01 06:03 PM
Re: Get size of all users My Documents and Desktops to text file

You also got some copy paste errors in there. There's an ENDIF missing in the top portion of code, and a random ENDIF and NEXT at the end of the dirlist() function. Also missing the EndFunction at the end of dirlist().

ShaneEP
(MM club member)
2013-11-01 06:08 PM
Re: Get size of all users My Documents and Desktops to text file

Give this a shot...see what you get. Also Im assuming the Host paths are displaying correctly to the screen when it runs? Is there a backslash at the end of the hosts in the file?

This
$HostPath = '\\' + $Host + 'C$\users'
may need to be
$HostPath = '\\' + $Host + '\C$\users'

 Code:
$aTargets = FileIO('c:\scripts\hosts.txt', 'R')
For Each $Host in $aTargets
   ; run code to query each $Host value
   If Ping($Host)
      $HostPath = '\\' + $Host + 'C$\users'
      'Processing ' $HostPath ? ; for debugging or status reporting

      ; run any necessary command using $HostPath to reference the target path
      $logFile = @ScriptDir+"\Profile Sizes.ini"

      $profiles = DirList($HostPath, 3)

      For Each $profile in $profiles
         If Right($profile, 1) = "\"
            $profilename = Split($profile, "\")
            $profilename = $profilename[UBound($profilename)-1]
            $nul = WriteProfileString($logfile, $Host+"\"+$profilename, "Desktop", fnGetFolderProp($profile+"Desktop","Size"))
            $nul = WriteProfileString($logfile, $Host+"\"+$profilename, "Documents", fnGetFolderProp($profile+"My Documents","Size"))
         Endif
      Next
   Endif
Next


Function fnGetFolderProp($sFldr,$sProp)
   Dim $objFSO, $objFldr, $nul
   $objFSO = CreateObject("Scripting.FileSystemObject")
   If Not VarType($objFSO)=9 Exit 1 EndIf
   $objFldr = $objFSO.GetFolder($sFldr)
   If Not VarType($objFldr)=9 Exit 3 EndIf
   $nul=Execute("$$fnGetFolderProp = $$objFldr."+$sProp)
   If VarType($fnGetFolderProp)=0 Exit 87 EndIf
EndFunction

Function dirlist($dirname, optional $options)
  dim $filename, $counter, $filepath, $mask
  dim $list, $sublist, $subcounter
  $counter=-1
  $dirname=trim($dirname)
  if $dirname=''
    $dirname=@CURDIR
  endif
  if right($dirname,1)='\'
    $dirname=left($dirname,len($dirname)-1)
  endif
  if getfileattr($dirname) & 16
    $mask='*.*'
  else
    $mask=substr($dirname,instrrev($dirname,'\')+1)
    $dirname=left($dirname,len($dirname)-len($mask)-1)
  endif
  redim $list[10]
  $filename=dir($dirname+'\'+$mask)
  while $filename<>'' and @ERROR=0
    if $filename<>'.' and $filename<>'..'
      select
      case (getfileattr($dirname+'\'+$filename) & 16)
        if $options & 1
          $counter=$counter+1
          if $options & 2
            $list[$counter]=$dirname+'\'+$filename+'\'
          else
            $list[$counter]=$filename+'\'
          endif
        endif
        if ($options & 4)
          $sublist=dirlist($dirname+'\'+$filename+'\'+$mask,$options)
          if ubound($sublist)+1
            redim preserve $list[ubound($list)+ubound($sublist)+1]
            for $subcounter=0 to ubound($sublist)
              $counter=$counter+1
              if $options & 2
                $list[$counter]=$dirname+'\'+$filename+'\'+$sublist[$subcounter]
              else
                $list[$counter]=$filename+'\'+$sublist[$subcounter]
              endif
            next
          endif
        endif
      case ($options & 2)
        $counter=$counter+1
        $list[$counter]=$dirname+'\'+$filename
      case 1
        $counter=$counter+1
        $list[$counter]=$filename
      endselect
      if $counter mod 10
        redim preserve $list[$counter+10]
      endif
    endif
    $filename = dir('')
  loop
  if $counter+1
    redim preserve $list[$counter]
  else
    $list=''
  endif
  if $mask<>'*.*' and ($options & 4)
    $filename=dir($dirname+'\*.*')
    while $filename<>'' and @ERROR=0
      if $filename<>'.' and $filename<>'..'
        if (getfileattr($dirname+'\'+$filename) & 16)
          $sublist=dirlist($dirname+'\'+$filename+'\'+$mask,4)
          if ubound($sublist)+1
            redim preserve $list[ubound($list)+ubound($sublist)+1]
            for $subcounter=0 to ubound($sublist)
              $counter=$counter+1
              if $options & 2
                $list[$counter]=$dirname+'\'+$filename+'\'+$sublist[$subcounter]
              else
                $list[$counter]=$filename+'\'+$sublist[$subcounter]
              endif
            next
          endif
        endif
      endif
      $filename = dir('')
    loop
  endif
  if $counter+1
    redim preserve $list[$counter]
  else
    $list=''
  endif
  $dirlist=$list
endfunction

Function Ping($Computer,$GetIP,optional $LoopCount,optional $TimeOut)
if $GetIP
dim $ip, $ipfile, $
$ipfile = @scriptdir + '\ip.txt'
shell '%Comspec% /q /e:1024 /c for /F "tokens=2 delims=[]" %%i IN ('+ chr(39)
+ '"ping ' + $Computer + ' -n 1 | find "]""' + chr(39) + ') do echo %%i >"' + $ipfile + '"'
$ = open(10,$ipfile,2) $ip = readline(10) $ = close(10) del $ipfile
if $ip
$Ping = $ip
else
$Ping = 'Bad IP address ' + $Computer + '!'
endif
exit 0
else
if $TimeOut
for $c = 0 to $LoopCount
shell '%Comspec% /C ping ' + $Computer + ' -n 1 -w ' + $TimeOut + ' | find /C "TTL=" > nul'
if @error = 0
$Ping = 1
exit 0
endif
next
else
for $c = 0 to $LoopCount
shell '%Comspec% /C ping ' + $Computer + ' | find /C "TTL=" > nul'
if @error = 0
$Ping = 1
exit 0
endif
next
endif
$Ping = 0
endif
EndFunction


Glenn BarnasAdministrator
(KiX Supporter)
2013-11-01 06:28 PM
Re: Get size of all users My Documents and Desktops to text file

George -

Please put your code in [ code ] tags!

You don't say why it isn't working or what error you're getting.

My earlier example depends on the Ping UDF from my site, which uses positive logic. Many of the other UDFs use negative logic, which will require additional coding to make it work. Not sure of the UDF you're using as it's quite old and has external dependencies, but you should verify that it returns with non-zero values on success.

Positive logic returns a TRUE state with an error code of zero on success, or a FALSE state and a non-zero error code on failure. This allows simple
 Code:
If Function()
  ; do stuff
Else
  ; choke - gasp! FAILED! Check error code!
EndIf
logic to be employed. Negative logic returns FALSE (zero) with an error code of zero on success and a TRUE with a non-zero error code on failure. This requires logic similar to this:
 Code:
If Function() = 0 ; or - If NOT Function(), which is counter-intuitive
  ; success - do stuff
Else
  ; choke - gasp! FAILED! Check error code!
EndIf
Glenn


GeorgeLittle
(Fresh Scripter)
2013-11-04 11:02 AM
Re: Get size of all users My Documents and Desktops to text file

So when I run it I get an Error Expected ')'! Line 1

ShaneEP
(MM club member)
2013-11-04 06:12 PM
Re: Get size of all users My Documents and Desktops to text file

And did you add the FileIO() function, like I mentioned in one of the previous suggestions?

ShaneEP
(MM club member)
2013-11-04 06:12 PM
Re: Get size of all users My Documents and Desktops to text file

 Code:
$aTargets = FileIO('c:\scripts\hosts.txt', 'R')
For Each $Host in $aTargets
   ; run code to query each $Host value
   If Ping($Host)
      $HostPath = '\\' + $Host + '\C$\users'
      'Processing ' $HostPath ? ; for debugging or status reporting

      ; run any necessary command using $HostPath to reference the target path
      $logFile = @ScriptDir+"\Profile Sizes.ini"
      $profiles = DirList($HostPath, 3)

      For Each $profile in $profiles
         If Right($profile, 1) = "\"
            $profilename = Split($profile, "\")
            $profilename = $profilename[UBound($profilename)-1]
            $nul = WriteProfileString($logfile, $Host+"\"+$profilename, "Desktop", fnGetFolderProp($profile+"Desktop","Size"))
            $nul = WriteProfileString($logfile, $Host+"\"+$profilename, "Documents", fnGetFolderProp($profile+"My Documents","Size"))
         Endif
      Next
   Endif
Next


Function fnGetFolderProp($sFldr,$sProp)
   Dim $objFSO, $objFldr, $nul
   $objFSO = CreateObject("Scripting.FileSystemObject")
   If Not VarType($objFSO)=9 Exit 1 EndIf
   $objFldr = $objFSO.GetFolder($sFldr)
   If Not VarType($objFldr)=9 Exit 3 EndIf
   $nul=Execute("$$fnGetFolderProp = $$objFldr."+$sProp)
   If VarType($fnGetFolderProp)=0 Exit 87 EndIf
EndFunction

Function dirlist($dirname, optional $options)
  dim $filename, $counter, $filepath, $mask
  dim $list, $sublist, $subcounter
  $counter=-1
  $dirname=trim($dirname)
  if $dirname=''
    $dirname=@CURDIR
  endif
  if right($dirname,1)='\'
    $dirname=left($dirname,len($dirname)-1)
  endif
  if getfileattr($dirname) & 16
    $mask='*.*'
  else
    $mask=substr($dirname,instrrev($dirname,'\')+1)
    $dirname=left($dirname,len($dirname)-len($mask)-1)
  endif
  redim $list[10]
  $filename=dir($dirname+'\'+$mask)
  while $filename<>'' and @ERROR=0
    if $filename<>'.' and $filename<>'..'
      select
      case (getfileattr($dirname+'\'+$filename) & 16)
        if $options & 1
          $counter=$counter+1
          if $options & 2
            $list[$counter]=$dirname+'\'+$filename+'\'
          else
            $list[$counter]=$filename+'\'
          endif
        endif
        if ($options & 4)
          $sublist=dirlist($dirname+'\'+$filename+'\'+$mask,$options)
          if ubound($sublist)+1
            redim preserve $list[ubound($list)+ubound($sublist)+1]
            for $subcounter=0 to ubound($sublist)
              $counter=$counter+1
              if $options & 2
                $list[$counter]=$dirname+'\'+$filename+'\'+$sublist[$subcounter]
              else
                $list[$counter]=$filename+'\'+$sublist[$subcounter]
              endif
            next
          endif
        endif
      case ($options & 2)
        $counter=$counter+1
        $list[$counter]=$dirname+'\'+$filename
      case 1
        $counter=$counter+1
        $list[$counter]=$filename
      endselect
      if $counter mod 10
        redim preserve $list[$counter+10]
      endif
    endif
    $filename = dir('')
  loop
  if $counter+1
    redim preserve $list[$counter]
  else
    $list=''
  endif
  if $mask<>'*.*' and ($options & 4)
    $filename=dir($dirname+'\*.*')
    while $filename<>'' and @ERROR=0
      if $filename<>'.' and $filename<>'..'
        if (getfileattr($dirname+'\'+$filename) & 16)
          $sublist=dirlist($dirname+'\'+$filename+'\'+$mask,4)
          if ubound($sublist)+1
            redim preserve $list[ubound($list)+ubound($sublist)+1]
            for $subcounter=0 to ubound($sublist)
              $counter=$counter+1
              if $options & 2
                $list[$counter]=$dirname+'\'+$filename+'\'+$sublist[$subcounter]
              else
                $list[$counter]=$filename+'\'+$sublist[$subcounter]
              endif
            next
          endif
        endif
      endif
      $filename = dir('')
    loop
  endif
  if $counter+1
    redim preserve $list[$counter]
  else
    $list=''
  endif
  $dirlist=$list
endfunction

Function FileIO($_File, $_Mode, OPTIONAL $_aData, OPTIONAL $_Opts)
  Dim $_				; temp var 
  Dim $_I				; index pointer 
  Dim $_Fp				; file pointer 
  Dim $_Fm				; file I/O mode 
  Dim $_Term				; line terminator 
  Dim $_NoNul				; Null line suppression flag 
  Dim $_FTerm				; final line term 
  Dim $_Prog				; Progress indicator flag 
  $FileIO = 0				; return fail by default 
  ; set the process options 
  $_Term  = IIf($_Opts & 1, Chr(10), @CRLF)
  $_NoNul = IIf($_Opts & 2, 1, 0)
  $_FTerm = IIf($_Opts & 4, '', $_Term)
  $_Prog  = IIf($_Opts & 8, 1, 0)
  ; validate the mode & set the I/O mode 
  $_Mode = Left($_Mode, 1)
  Select
   Case $_Mode = 'R'			; read 
    $_Fm = 2
   Case $_Mode = 'W'			; write/create 
    If VarType($_aData) < 8192
      Exit 87				; exit with error if Write/Create mode and no data 
    EndIf
    $_Fm = 5
    If Exist($_File)			; remove any existing file if not in Append mode 
      Del $_File
    EndIf
   Case $_Mode = 'A'			; append 
    If VarType($_aData) < 8192
      Exit 87				; exit with error if Write/Append mode and no data 
    EndIf
    $_Fm = 5
   Case 1				; invalid mode 
    Exit 87
  EndSelect
  ; locate an available file handle 
  $_Fp = FreeFileHandle
  If Not $_Fp
    Exit 1
  EndIf
  ; Open the file in the defined input or output mode - exit if the open fails 
  $_ = Open($_Fp, $_File, $_Fm)
  If @ERROR Exit @ERROR EndIf
  If $_Fm = 2				; read file 
    ReDim $_aData[499]			; start w/ 500 lines 
    $_I = -1
    $_ = ReadLine($_Fp)
    While Not @ERROR
      $_I = $_I + 1
      $_aData[$_I] = $_
      If $_I > 1 And $_I Mod 499 = 0
        ReDim Preserve $_aData[$_I + 500]
        If $_Prog '.' EndIf		; progress marker 
      EndIf
      $_ = ReadLine($_Fp)
    Loop
    $_ = Close($_Fp)
    ReDim Preserve $_aData[$_I]
    If $_Prog '. ' EndIf
    $FileIO = $_aData
    Exit 0
  Else					; write file 
    For $_I = 0 to UBound($_aData) - 1
      If $_NoNul
        If $_aData[$_I]			; write if not null 
          $_ = WriteLine($_FP, $_aData[$_I] + $_Term)
        EndIf
      Else				; write always 
        $_ = WriteLine($_FP, $_aData[$_I] + $_Term)
      EndIf
      If $_I > 1 And $_I Mod 499 = 0 And $_Prog '.' EndIf
    Next
    ; write last line 
    If $_NoNul
      If $_aData[$_I]			; write if not null 
        $_ = WriteLine($_FP, $_aData[$_I] + $_FTerm)
      EndIf
    Else				; write always 
      $_ = WriteLine($_FP, $_aData[$_I] + $_FTerm)
    EndIf
    $_ = Close($_Fp)
    $FileIO = 1				; show a completed write 
    If $_Prog '. ' EndIf
    Exit 0
  EndIf
EndFunction

Function Ping($_Host, OPTIONAL $_Flag, OPTIONAL $_Wait)
  Dim $_oExec				; WSH Object 
  Dim $_Tries				; # of times to ping 
  Dim $_Timeout				; Ping timeout value 
  Dim $_Response			; Response Flag 
  Dim $_Line				; Line returned from command string 
  Dim $_Cmd				; first part of command string 
  Dim $_Count				; current ping count 
  $_Flag    = Val($_Flag)		; determine what to do 
  $_Wait    = Val($_Wait)		;  
  $_Tries   = 1				; one ping 
  $_Timeout = 1000			; 1 second timeout 
  ; set timeout if Wait is non-zero 
  If $_Wait > 0
    $_Timeout = $_Wait
  EndIf
  If $_FLAG > 0        ; Multiple pings - return on first reply 
    $_Tries = $_FLAG
  EndIf
  ; Ping the host $_Tries times, but only until a response is received 
  $_Count = 0
  ; search for reply from host during PING 
  $_Cmd = '%COMSPEC% /c ping.exe -4 -n 1 -w ' + $_Timeout + ' ' + $_Host 
  If $_Flag < 0
    $_Cmd = $_Cmd + ' | %SystemRoot%\System32\Find "Pinging"'
  Else
    $_Cmd = $_Cmd + ' | %SystemRoot%\System32\Find "Reply" | %SystemRoot%\System32\Find "TTL="'
  EndIf
  Do
    $_oExec = CreateObject("WScript.Shell").Exec($_Cmd)
    If Not VarType($_oExec)=9 $Ping = 'WScript.Shell Exec Unsupported' Exit 10 EndIf
    $_Line = Split(Join(Split($_oExec.StdOut.ReadAll + $_oExec.StdErr.ReadAll,CHR(13)),''),CHR(10))[0]
    $_Response = IIf($_Line, 1, 0)
    If $_Response
      $_Count = $_Tries
    EndIf
    $_Count = $_Count + 1
    If $_Count <  $_Tries Sleep 0.25 EndIf
  Until $_Count >= $_Tries
  ; If FLAG >= 0, return success/failure - otherwise return IP address 
  If $_FLAG >= 0
    $Ping = $_Response
  Else
    If Not $_Response
      $Ping = '0.0.0.0'
    Else
      ; In this mode we return the IP address - we should have the HOSTNAME 
      ; handle the 'duh' factor for times when we get the IP address instead! 
      If InStr($_Line,'[') > 0
        $Ping= Split(Join(Split($_Line,']',-1),'['), '[')[1]
      Else
        $Ping = Split(Split($_Line,' ',-1)[1], ':')[0]
      EndIf
    EndIf
  EndIf
  Exit Not $_Response       ; set the error code 
EndFunction


GeorgeLittle
(Fresh Scripter)
2013-11-05 10:04 AM
Re: Get size of all users My Documents and Desktops to text file

That is now working a treat ! Thanks so much guys \:D

NTDOCAdministrator
(KiX Master)
2013-11-08 09:28 AM
Re: Get size of all users My Documents and Desktops to text file

I might have to give this code a spin just for fun

Thanks everyone involved in this coding