用VBScript的FSO对象读取icacls / save的结果失败

时间:2017-12-06 12:34:20

标签: vbscript icacls

我需要保存运行ICACLS命令的结果,更改它们,然后恢复更改的权限。我使用vbscript来做到这一点。问题是从保存中读取行或整个数据会给我1个字符和一堆空格。但是,如果我尝试读取结果数据的内容,由ICACLS上传,char-by-char,并在运行中打印它,它会显示正确的内容。

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

我怀疑,问题出在ICACLS本身:它没有写出真正的文本文件。我找到了另一个遇到这种情况的人(https://windowssecrets.com/forums/showthread.php/150866-Win7-ICACLS-redirected-output-and-NOTEPAD-don-t-play-well-together)。

P.S:CACLS写出正确读取的正确文本文件。但不幸的是,它无法在整个文件夹中进行递归。

1 个答案:

答案 0 :(得分:0)

通过阅读数百页,我终于找到了解决方案!此函数将icacls <file or folder> /save <filename> /T创建的文本从UCS-2代码页转换为UTF-8:

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

之后,使用VBScript可以读取生成的文本。

从这里得到答案:UCS-2 Little Endian to UTF-8 conversion leaves file with many unwanted characters