通过单击批处理文件上的按钮来执行Powershell文件

时间:2019-06-28 19:38:41

标签: powershell batch-file

我正在尝试编写一个批处理文件,该批处理文件通过单击界面上的按钮来执行不同的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>

我试图在不单击按钮的情况下运行代码,并且效果很好。我希望它在按不同按钮时执行某些文件。

1 个答案:

答案 0 :(得分:0)

您应在批处理文件中执行PowerShell代码 。您不能从Web / HTA页面直接执行PowerShell(也不能执行批处理文件)。

为此,您需要遵循this answer上的建议。

<!-- :: 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>