transfer CurrentDirectory from un-elevated script to elevated one

前端 未结 1 1088
一向
一向 2021-01-21 16:00

I need to copy my file \"manufacturer.bmp\", wich is located in the same directory as the script (in my flash drive), to the system32 directory.

I succeed,

相关标签:
1条回答
  • 2021-01-21 16:20

    The ShellExecute method allows you to specify the working directory as the 3rd argument, so you can pass the current directory to the elevated script and build the sourcefile path after elevation. Also, your code could be streamlined quite a bit.

    Const HKLM   = &h80000002
    Const DELETE = &h10000
    
    Set sh = CreateObject("WScript.Shell")
    
    Set reg = GetObject("winmgmts://./root/default:StdRegProv")
    reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
    
    If Not isAdmin Then
      If WScript.Arguments.Count = 0 Then
        CreateObject("Shell.Application").ShellExecute WScript.FullName, _
          Chr(34) & WScript.ScriptFullName & Chr(34) & " uac", _
          sh.CurrentDirectory, "runas", 1
        WScript.Quit 0
      Else
        WScript.Echo "Privilege elevation failed!"
        WScript.Quit 1
      End If
    End If
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
    dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
    
    fso.CopyFile src, dst & "\"
    

    Edit: or at least that's how it would work if you weren't elevating the process. According to this blog post from Raymond Chen the start directory is ignored when elevating processes, so that malicious DLLs from the current directory aren't loaded into elevated processes by mistake. Meaning that you must pass the working directory "manually", like this:

    Const HKLM   = &h80000002
    Const DELETE = &h10000
    
    Set sh = CreateObject("WScript.Shell")
    
    Set reg = GetObject("winmgmts://./root/default:StdRegProv")
    reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
    
    If Not isAdmin Then
      If WScript.Arguments.Count = 0 Then
        CreateObject("Shell.Application").ShellExecute WScript.FullName, _
          Chr(34) & WScript.ScriptFullName & Chr(34) & " " & _
          Chr(34) & sh.CurrentDirectory & Chr(34), , "runas", 1
        WScript.Quit 0
      Else
        WScript.Echo "Privilege elevation failed!"
        WScript.Quit 1
      End If
    End If
    
    sh.CurrentDirectory = WScript.Arguments(0)
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
    dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
    
    fso.CopyFile src, dst & "\"

    Note that since your destination path is a folder, it must have a trailing backslash (as documented).

    0 讨论(0)
提交回复
热议问题