首页 > 解决方案 > Filesystemobject Textstream,在执行 Textstream.Close 时立即消失(正在创建.vbs 扩展名)

问题描述

我的情况真的让我很困惑。我多年来使用的简单代码以最奇怪的方式失败。我感觉原因与反病毒垃圾或 GPO 有关,但是,即使是那些,我也曾看到它们在这种情况下运行过——但与我现在看到的完全不同。 注意 - 这段代码对几个人来说都很好,直到一个最终用户从 IT 部门获得了一台新的 Surface 笔记本电脑,据称是为了更好地与 Teams 和 365 兼容。所有用户(工作的,非工作的)都在 Windows 10 上。

设想:

  1. 我正在使用 Scripting.Filesystemobject
  2. 设置对象变量(Textstream 意图),如 fso.createtextfile
  3. 我正在创建的文件路径(名称)实际上是filename.vbs...在这一行执行的那一刻,我可以在文件夹中看到vbs文件成功
  4. 我使用 Textstream.Write 将一些内容放入文件中
  5. 然后我使用 Textstream.Close(通常此时您会得到一个可靠、稳定、可用的文件)。 在执行最后一行 Textstream.Close 后,该文件立即从文件夹 GONE 中消失。

我要写入的文件夹与 Start > Run > %appdata% 我也在 Documents 文件夹 (Environ$("USERPROFILE") & "\My Documents") 中尝试过,并得到完全相同的结果

我已经看到会阻止 VBS 运行的组策略和 AV 内容,但这不是我的情况——我已经对这个用户进行了测试,她没有问题:

  1. 在这些文件夹中的任何一个中创建一个 txt 文件
  2. 在任一文件夹中手动创建 .vbs 文件
  3. 甚至在任一文件夹中运行生成的 vbs 文件

但不知何故,当我以编程方式在代码中创建 .VBS 时,第二次关闭文本流时,文件就从文件夹中消失了。

有什么见解吗?我所做的互联网搜索没有关于这种情况的所有信息!我需要 2 周时间才能开票并从 IT 部门获得任何帮助

这是 Excel VBA,但我非常怀疑这个问题与 Excel 或 VBA 有什么关系……这是 windows scripting.filesystemobject 的标准用法:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
'initiate full backup vbs script:
Dim ts As Object, fso As Object, strScriptText As String, strScriptPath As String
'populate our variable with the full text of the script: found on QLoader in this range:
strScriptText = ThisWorkbook.Worksheets("QLoader").Range("z_BackupScriptText").Value
'replace the text "placeholder" with this workbook's actual full path/name:
strScriptText = Replace(strScriptText, "placeholder", ThisWorkbook.FullName)

'fire up FSO:
Set fso = CreateObject("scripting.filesystemobject")
'determine the new VBS file's path
strScriptPath = Environ("AppData") & "\Backup_" & Format(Now, "yymmddhhmmss") & ".vbs"
'create our textstream object:
Set ts = fso.createtextfile(strScriptPath)
'write our script into it
ts.write strScriptText
'save and close it
ts.Close 'RIGHT HERE THE FILE DISAPPEARS FROM THE FOLDER ***********

'GO:
Shell "wscript " & strScriptPath, vbNormalFocus

End Sub

标签: vbaantivirusgroup-policyfilesystemobject

解决方案


它看起来确实像一个杀毒软件......

如果问题只是vbs扩展名,您可以使用以下内容:

Sub tester()

    Dim ts As Object, fso As Object, strScriptText As String, strScriptPath As String
    
    Set fso = CreateObject("scripting.filesystemobject")
    
    strScriptPath = Environ("AppData") & "\Backup_" & Format(Now, "yymmddhhmmss") & ".txt"
    
    Set ts = fso.createtextfile(strScriptPath)
    
    ts.write "Msgbox ""Hello"""
    
    ts.Close
    
    'need to specify the script engine to use
    Shell "wscript.exe /E:vbscript """ & strScriptPath & """ ", vbNormalFocus

End Sub

推荐阅读