在%temp%中创建一个文本文件,然后使用vbs在其中写入内容

时间:2018-10-15 15:43:53

标签: vbscript ms-office special-folders micro

基本上,我想创建一个新文件并将其写入PC上由%TEMP%变量指向的目录中。但是,以下修改后的代码不起作用:

Dim oFile
Dim shell
Set oShell = CreateObject("WScript.Shell")
user = oShell.ExpandEnvironmentStrings("%Temp%")
Set oFile = CreateObject("Wscript.Shell")
Set oFile = oFile.CreateTextFile("%Temp%\d.txt")
oFile.WriteLine "here is my contant"
oFile.Close

错误消息:

  

运行时错误
  行号:3
  需要对象

旧代码

Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
FileName = "%TEMP%\myfile.txt"
Set tf = fso.CreateTextFile(FileName, True)

如果我使用文件名“ C:\ myfile.txt”,则可以正常工作。

错误消息:

  

找不到路径

2 个答案:

答案 0 :(得分:0)

您可以使用Environ("temp")来写入C:\Users\[username]\AppData\Local\Temp

答案 1 :(得分:0)

在VBA中,您可以仅使用Environ("TEMP")来扩展Environment变量-如果这在VBScript中不起作用,则可能需要绑定WScript.Shell对象并使用ExpandEnvironmentStrings属性,例如所以:

Set oShell = CreateObject("WScript.Shell")
FileName = oShell.ExpandEnvironmentStrings("%TEMP%") & "\myfile.txt"
Set oShell = Nothing

下面的评论

这是一个“完全固定”的代码:

'Declare variables/objects first
Dim fso AS Object, oFile AS Object
Dim oShell AS Object, FileName AS String

'This bit turns "%TEMP%" into a real file path
Set oShell = CreateObject("WScript.Shell")
FileName = oShell.ExpandEnvironmentStrings("%Temp%\d.txt")
Set oShell = Nothing 'Tidy up the Objects we no longer need

'This bit creates the file
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(FileName)
oFile.WriteLine "here is my content"
oFile.Close
Set oFile = Nothing 'Tidy up the Objects we no longer need
Set fso = Nothing 'Tidy up the Objects we no longer need