Cmd 脚本无法正常工作

Cmd 脚本无法正常工作

我创建了一个通过添加兼容模式的脚本cmd,但是在使其运行时遇到了问题:

Reg Add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" /v "%CD%\mha2.exe" /t REG_SZ /d "WINXPSP3 256COLOR 640X480" /f

:: # For testing only:
   MkDir Success
   Exit
  • 通过 GUI 执行脚本时,Success会创建目录,但不会设置兼容模式;无论我是否使用管理员权限运行脚本,都没有关系
  • 当通过以下方式以管理员权限执行脚本时,它会执行所有应该执行的操作:
    Start "C:\Path\To\script.bat"
    

为什么会出现这种情况?我该如何解决?

答案1

经过几个小时的工作,我明白了:在 之前包含一行代码时,需要管理员权限才能启动脚本Reg Add,因为cmd会在 中启动它%WinDir%\system32

  • 如果有人想做同样的事情:
    @echo off
    
    :: # BatchGotAdmin
    :-------------------------------------
    REM # --> Check for permissions
      if "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
        >nul 2>&1 "%SystemRoot%\SysWOW64\cacls.exe" "%SystemRoot%\SysWOW64\config\system"
      ) else (
        >nul 2>&1 "%SystemRoot%\system32\cacls.exe" "%SystemRoot%\system32\config\system"
      )
    
    REM # --> If error flag set, we do not have admin.
      if '%errorlevel%' NEQ '0' (
        Echo "Requesting administrative privileges..."
        GoTo UACPrompt
      ) else ( GoTo GotAdmin )
    
    :UACPrompt
      Echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
      Set params= %*
      Echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"
    
      "%temp%\getadmin.vbs"
      Del "%temp%\getadmin.vbs"
      Exit /b
    
    :GotAdmin
      Pushd "%CD%"
      Cd /d "%~dp0"
    :--------------------------------------
    
    Reg Add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" /v "%CD%\mha2.exe" /t REG_SZ /d "WIN98 256COLOR 640X480" /f
    

答案2

@echo off && Setlocal EnableDelayedExpansion

2>nul "%__APPDIR__%whoami.exe" /groups | find "S-1-16-12288" >nul && goto=:gotAdmin 

echo\Requesting administrative privileges... && set "_args=%*" && set "_flag=1" && >"%temp%\getadmin.vbs" ^
echo=CreateObject("Shell.Application"^).ShellExecute "%~sdpnx0", "!_args:"=""!", "RunAsAdministrator", "runas", 1 :WScript.Quit 

%__AppDir__%cscript.exe "%temp%\getadmin.vbs"|find/v "." & echo\<nul & cd. & 2>nul del /q /f "%temp%\getadmin.vbs" && goto=:EOF 

:gotAdmin
cd /d "%~dp0" && set "_Reg_Key=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"
%__AppDir__%reg.exe add "!_Reg_Key!" /v \""!CD!\Launcher.exe\"" /t REG_SZ /d "WIN98 256COLOR 640X480" /f
 
2>&1 %__AppDir__%reg.exe Query "!_Reg_Key!"|%__AppDir__%findstr.exe /i Launcher.exe.*WIN98.256COLOR.640X480 && ^
echo\Requesting admin works || echo\Not works, sorry... & %__AppDir__%timeout.exe /t -1 && endlocal && goto=:EOF

使用另一个命令来简化管理员权限的验证怎么样:

ExecuteCMD && return 0 and I'm the admin and goto label :gotAdmin
The last command was unsuccessful because I'm not the admin and now I'll create and call vbs file... 


Whoami.exe | find "S-1-16-12288" && goto=:gotAdmin 
The last command was unsuccessful because I'm not the admin and now I'll create and call vbs file...  

相关内容