如何将PHP数组直接作为参数传入PowerShell exec命令?
解决方案
你的思路是可行的,但当前代码存在几个关键问题,导致PowerShell无法正确解析数组参数。以下是两种可靠的实现方式,以及对现有代码的修正建议:
方法一:将数组元素作为独立命令行参数传递
这种方式最直接,把每个组名作为单独的参数传给PowerShell脚本,再在脚本中收集为数组。
修改后的PHP代码
<?php $Psscript = 'C:\Scripts\script.ps1'; // 用单引号避免反斜杠转义问题 $arg1 = $_POST["arg1"]; $arg2 = $_POST["arg2"]; $groups = $_POST["groups"]; // 对每个参数进行命令行转义,处理空格、特殊字符 $escapedArgs = array_map(function($val) { return escapeshellarg($val); }, array_merge([$arg1, $arg2], $groups)); $commandArgs = implode(' ', $escapedArgs); // 使用-File参数而非-Command,确保参数正确传递给脚本 $result = shell_exec("powershell -InputFormat none -ExecutionPolicy ByPass -NoProfile -File $Psscript $commandArgs 2>&1"); echo $result; ?>
修改后的PowerShell脚本
###### Args ###### $arg1 = $args[0] $arg2 = $args[1] # 从第3个参数开始,所有参数都是组名,组成数组 $groups = $args[2..($args.Count - 1)] $fullname = "$arg1.$arg2" # 修正会话变量名的笔误(原代码中$session和$sessionAD不一致) if (-not $session) { $session = New-PSSession -ComputerName 'srv01' -ConfigurationName "Microsoft.PowerShell32" -Credential $cred } Invoke-Command -Session $session -ScriptBlock { Import-Module ActiveDirectory foreach ($group in $using:groups) { Add-ADGroupMember -Identity $group -Members $using:fullname } } Remove-PSSession $session
方法二:用JSON序列化传递数组
通过JSON格式将PHP数组序列化为字符串,在PowerShell中解析为数组,适合复杂结构的参数传递。
修改后的PHP代码
<?php $Psscript = 'C:\Scripts\script.ps1'; $arg1 = $_POST["arg1"]; $arg2 = $_POST["arg2"]; // 将数组序列化为JSON字符串 $groupsJson = json_encode($_POST["groups"]); // 转义为安全的命令行参数 $escapedGroupsJson = escapeshellarg($groupsJson); $result = shell_exec("powershell -InputFormat none -ExecutionPolicy ByPass -NoProfile -File $Psscript $arg1 $arg2 $escapedGroupsJson 2>&1"); echo $result; ?>
修改后的PowerShell脚本
###### Args ###### $arg1 = $args[0] $arg2 = $args[1] # 将JSON字符串解析为PowerShell数组 $groups = $args[2] | ConvertFrom-Json $fullname = "$arg1.$arg2" if (-not $session) { $session = New-PSSession -ComputerName 'srv01' -ConfigurationName "Microsoft.PowerShell32" -Credential $cred } Invoke-Command -Session $session -ScriptBlock { Import-Module ActiveDirectory foreach ($group in $using:groups) { Add-ADGroupMember -Identity $group -Members $using:fullname } } Remove-PSSession $session
额外注意事项
- 路径转义:PHP中Windows路径要用单引号包裹,或者把反斜杠转义为
\\,避免被解析为转义字符。 - 变量笔误:原PowerShell脚本中
$session和$sessionAD变量名不一致,会导致会话无法调用,需统一。 - 凭据安全:
$cred变量需要提前定义(比如通过Get-Credential或安全的凭据存储方式),避免硬编码密码。 - 输入验证:务必对
$_POST中的参数进行验证(比如组名格式检查),防止命令注入或无效AD操作。
内容的提问来源于stack exchange,提问作者Ben74
相关产品推荐
相关产品推荐

