从批处理文件上的按钮单击执行PowerShell文件



我正在尝试编写一个批处理文件,该文件在接口上的按钮上单击执行不同的PowerShell文件。

<!-- :: Batch section
@echo off
SET "ThisScriptsDirectory=%~dp0"
SET "PowerShellScriptPathAdd=%ThisScriptsDirectory%powershelladd.ps1"
SET "PowerShellScriptPathRemove=%ThisScriptsDirectory%powershellremove.ps1"
#PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process 
PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPathAdd%""'}"

echo Select an option:
for /F "delims=" %%a in ('mshta.exe "%~F0"') do set "HTAreply=%%a"
echo End of HTA window, reply: "%HTAreply%"
goto :EOF
-->

<HTML>
<HEAD>
<HTA:APPLICATION SCROLL="no" SYSMENU="no" >
<TITLE>HTA Buttons</TITLE>
<SCRIPT language="JavaScript">
window.resizeTo(374,100);
function closeHTA(reply){
   var fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.GetStandardStream(1).WriteLine(reply);
   window.close();
}
</SCRIPT>
</HEAD>
<BODY>
   <button onclick=PowerShell -NoProfile -ExecutionPolicy Bypass -Command 
"& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy 
Bypass -File ""%PowerShellScriptPathAdd%""'}">Add User</button>
   <button onclick=PowerShell -NoProfile -ExecutionPolicy Bypass -Command 
"& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy 
Bypass -File ""%PowerShellScriptPathRemove%""' -Verb RunAs}">Remove 
User</button>
   <button onclick="closeHTA(3);">Exit</button>
</BODY>
</HTML>

我尝试在不单击按钮的情况下运行代码,并且可以正常运行。我希望它按下不同的按钮时执行某些文件。

您应该在批处理文件中执行PowerShell代码。您无法直接执行Web/HTA页面的PowerShell(也不是批处理文件(。

为了这样做,您需要遵循此答案中给出的建议。

<!-- :: Batch section
@echo off
setlocal
rem Initialize Batch side interface the first time
if "%~1" equ "interface" goto :interface
rem Empty pipe file
cd . > pipeFile.txt
echo Select an option:
rem Start HTA-Batch interface
mshta.exe "%~F0" >> pipeFile.txt  |  "%~F0" interface < pipeFile.txt
PAUSE
del pipeFile.txt
goto :EOF

:interface
set "HTAreply="
set /P "HTAreply="
if "%HTAreply%" equ "" goto interface
if "%HTAreply%" == "1" PowerShell 'Add user here...'
if "%HTAreply%" == "2" PowerShell 'Remove user here...'
if not "%HTAreply%" == "3" goto interface
echo End of HTA window
goto :EOF
-->

<HTML>
<HEAD>
<HTA:APPLICATION SCROLL="no" SYSMENU="no" >
<TITLE>HTA Buttons</TITLE>
<SCRIPT language="JavaScript">
window.resizeTo(374,100);
var fso = new ActiveXObject("Scripting.FileSystemObject");
function replyHTA(reply){
   fso.GetStandardStream(1).WriteLine(reply);
}
</SCRIPT>
</HEAD>
<BODY>
   <button onclick="replyHTA(1);">Add User</button>
   <button onclick="replyHTA(2);">Remove User</button>
   <button onclick="replyHTA(3);window.close();">Exit</button>
</BODY>
</HTML>

最新更新