如果我想在用户的桌面上创建文件,如何避免使用绝对文件路径?

时间:2017-02-08 23:36:58

标签: vbscript filepath desktop

现在我的脚本在已知用户的桌面上使用绝对文件路径作为输出文件夹,但如果我想允许脚本在用户名为I的用户的桌面上工作,该怎么办? 知道吗?

示例 - 这里是我目前正在使用的线路。它工作正常,但显然只适用于约翰"。我需要使用任何可能的用户名 - 汤姆,迪克,哈利等等。

' Creating log repository
objFSO.CreateFolder "C:\Users\John\Desktop\Output"

2 个答案:

答案 0 :(得分:0)

简单的方法但如果桌面不在用户的通常位置则会失败,这可能是合作的环境。

dir "%userprofile%\Desktop"

更好的方法是

for /f "skip=2 tokens=3" %A in ('Reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Desktop"') do set doc=%A

dir "%doc%" /a

(在批处理中记住%%A,如果输入则记住%A我认为你的问题是批处理。在VBScript中,这两种方法都很简单。

set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%userprofile%\Desktop\Output")

bKey = WshShell.RegRead("HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop")

     strDesktop = WshShell.SpecialFolders("Desktop")

答案 1 :(得分:0)

为了避免在评论中进行扩展讨论,我在这里放置了一个不言自明的例子。

' helper function to quote strings
' useful in commands
Function Quot(str)
    Quot = Chr(34) & str & Chr(34)
End Function

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set WshShell = CreateObject("Wscript.Shell")

' get user's desktop directory and introduce a variable
currentDesktop = WshShell.SpecialFolders("Desktop") 'another way to do it

' introduce output directory variable <currentDesktop>\Output
outputDir = objFSO.BuildPath(currentDesktop, "Output")

' create <outputDir> if not exists
If Not objFSO.FolderExists(outputDir) Then 
    objFSO.CreateFolder outputDir
End If

' example usage in a command
' send command output to <outputDir>\network_config.txt
WshShell.Run "%COMSPEC% /c ipconfig /all >" & Quot(objFSO.BuildPath(outputDir, "network_config.txt"))