Windows Server 2022 上的 IIS 10 中运行 PowerShell 脚本,可以使用 CGI 模块配置来直接执行 .ps1 脚本,或者通过 ASP.NET 应用中的 C# 代码调用 PowerShell 脚本。如果您选择 CGI 方式,请确保启用了 CGI 模块并配置正确的路径和权限。
Windows Server 2022 上的 IIS 10 中运行 PowerShell 脚本需要进行一些特定配置,因为 IIS 本身并不直接支持 PowerShell 脚本执行。通常,这种配置是在 Web 应用或站点的服务器端运行 PowerShell 脚本时使用的。
要在 IIS 10 上运行 PowerShell 脚本,通常有两种方法:
- 通过 IIS 中的 CGI 模块配置执行 PowerShell 脚本
- 通过 ASP.NET 应用调用 PowerShell 脚本
以下是详细步骤:
1. 通过 IIS 中的 CGI 模块配置执行 PowerShell 脚本
CGI(Common Gateway Interface)是一个让 IIS 可以执行外部程序(如 PowerShell 脚本)的机制。
步骤:
-
启用 CGI 模块
首先,确保你的 IIS 上启用了 CGI 模块,因为 PowerShell 脚本将作为外部程序运行。
-
打开 Windows 功能:
- 在
开始菜单中,输入控制面板并打开它。 - 选择
程序>启用或关闭 Windows 功能。
- 在
-
在 IIS 功能 中,确保选中
CGI复选框。 -
你也可以通过 PowerShell 启用 CGI 模块:
powershellCopy CodeEnable-WindowsFeature Web-CGI
-
-
配置 IIS 执行 PowerShell 脚本
- 打开 IIS 管理器。
- 找到你想配置的 站点,然后点击站点名称。
- 在右侧的 功能视图 中,找到并双击 处理程序映射。
- 点击 添加脚本映射(右侧的操作栏)。
- 配置以下参数:
- 请求路径:
*.ps1(表示所有 PowerShell 脚本) - 可执行文件:浏览并选择 PowerShell 可执行文件路径,通常为
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe。 - 名称:
PowerShell(自定义名称)
- 请求路径:
- 点击 确定。
-
配置 PowerShell 执行策略
默认情况下,Windows PowerShell 的执行策略可能不允许脚本执行,因此你需要确保 PowerShell 的执行策略设置为允许脚本运行。使用管理员权限打开 PowerShell,然后执行以下命令:
powershellCopy CodeSet-ExecutionPolicy RemoteSigned -Scope LocalMachine这个命令允许本地脚本运行,而远程脚本需要签名。
-
测试 PowerShell 脚本
创建一个简单的 PowerShell 脚本,例如
test.ps1,然后将它放置到 IIS 网站的根目录或合适的目录中。例如,内容如下:powershellCopy CodeWrite-Host "Hello from PowerShell"通过浏览器访问
http://<your-server>/test.ps1,如果一切配置正确,PowerShell 脚本将被执行并输出结果。
2. 通过 ASP.NET 应用调用 PowerShell 脚本
如果你在 IIS 中运行的是 ASP.NET 应用,并希望通过该应用来运行 PowerShell 脚本,你可以使用 C# 中的 System.Management.Automation 命名空间来调用 PowerShell 脚本。
示例代码(在 ASP.NET 应用中调用 PowerShell 脚本):
using System.Management.Automation;
using System.Collections.ObjectModel;
public class PowerShellScriptExecutor
{
public string ExecutePowerShellScript(string script)
{
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.AddScript(script);
Collection<PSObject> results = powerShell.Invoke();
string output = string.Join(Environment.NewLine, results.Select(result => result.ToString()));
return output;
}
}
}
在你的 ASP.NET 控制器中,调用这个方法来执行 PowerShell 脚本并获取输出:
public ActionResult RunScript()
{
PowerShellScriptExecutor executor = new PowerShellScriptExecutor();
string scriptOutput = executor.ExecutePowerShellScript("Get-Process");
return Content(scriptOutput);
}
3. 注意事项:
-
权限设置:在 IIS 中运行 PowerShell 脚本时,确保
IIS AppPool使用的身份具有足够的权限来执行 PowerShell 脚本。通常,ApplicationPoolIdentity可能需要特定的权限来执行脚本,特别是当脚本涉及到文件或系统操作时。 -
防火墙和安全配置:确保 IIS 服务和相关的网络端口没有阻止 PowerShell 脚本执行,尤其是在企业环境中。
-
脚本调试:在生产环境中运行 PowerShell 脚本时,务必进行充分的脚本调试,避免恶意代码或安全漏洞。尽量避免让不受信任的用户上传或执行任意 PowerShell 脚本。
要在 Windows Server 2022 上的 IIS 10 中运行 PowerShell 脚本,可以使用 CGI 模块配置来直接执行 .ps1 脚本,或者通过 ASP.NET 应用中的 C# 代码调用 PowerShell 脚本。如果您选择 CGI 方式,请确保启用了 CGI 模块并配置正确的路径和权限。如果选择 ASP.NET 方式,您需要在服务器端代码中使用 System.Management.Automation 类库来执行脚本。

浙公网安备 33010602011771号