reading results of icacls /save with FSO object of VBScript fails

492 views Asked by At

I need to save the results of running ICACLS command, change them, and restore the changed permissions back. I use vbscript to do that. The issue is that reading lines or whole data from the saved gives me 1 character and a bunch of spaces in result. But if I try reading the contents of the resulting data, been uploaded by ICACLS, char-by-char, and printing it on the fly, it shows the proper contents.

Const ForReading=1 'I/O modes
dim FolderToSetPermissions,ShellObj,FSO,EffectivePermissionsFile,CurrentLine,ParentFolderName,ParentFolderObj
FolderToSetPermissions="c:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
ParentFolderName=FSO.GetParentFolderName(wscript.ScriptFullName)
Set ParentFolderObj =fso.GetFolder(ParentFolderName)    
Set ShellObj = WScript.CreateObject("WScript.Shell")
ShellObj.run "icacls.exe """&FolderToSetPermissions&"""\* /save " & ParentFolderObj.path & "\EffectivePermissions.txt /t", 0, True
set EffectivePermissionsFile =FSO.OpenTextFile(ParentFolderObj.path & "\EffectivePermissions.txt",ForReading,False)
Do Until EffectivePermissionsFile.AtEndOfStream
'CurrentLine=EffectivePermissionsFile.Read(1) ' works fine if prints right after 
 'reading from file. Concatenating all the chars in file causes the same result as 
 'reading the file by lines or with .ReadAll function of FSO
 CurrentLine= EffectivePermissionsFile.ReadLine
 WScript.Echo CurrentLine
Loop
EffectivePermissionsFile.Close

I suspect, the issue is in the ICACLS itself: it doesn't write a really text file. I found another person who run into the situation (https://windowssecrets.com/forums/showthread.php/150866-Win7-ICACLS-redirected-output-and-NOTEPAD-don-t-play-well-together).

P.S: CACLS writes correct text files which are read with no problems. But unfortunately it can't do a recurse throughout of a folder.

1

There are 1 answers

0
Yuri Oprischenko On

Reading through hundreds of pages I finally found the solution! This function converts the text created by icacls <file or folder> /save <filename> /T from UCS-2 codepage to UTF-8 one:

Sub UTFConvert(filename)
  Set fso = CreateObject("Scripting.FileSystemObject")
  txt = fso.OpenTextFile(filename, 1, False, -1).ReadAll

  Set stream = CreateObject("ADODB.Stream")
  stream.Open
  stream.Type     = 2 'text
  stream.Position = 0
  stream.Charset  = "utf-8"
  stream.WriteText txt
  stream.SaveToFile filename, 2
  stream.Close
End Sub

The resulting text becomes readable with VBScript afterwards.

Took the answer from here: UCS-2 Little Endian to UTF-8 conversion leaves file with many unwanted characters