直到最近,我的 PHP 脚本使用参数调用 Powershell 脚本都工作正常,但现在字符串应该是这种格式
@("grp1","grp2")
在 Powershell 端现在是 grp1 grp2
提交到Powershell之前PHP端的回显是
@(\"grp1\",\"grp2\")
$_POST["groups"] 是一个数组。
这是我的 PHP 代码:
<?php
$ADJoinGroups = "C:\Scripts\AD_Joingrps.ps1";
$entity = $_POST["entity"];
$fName = $_POST["fName"];
$lName = $_POST["lName"];
$desc = $_POST["description"];
$password = "#####";
$groups = '@(\"'.implode('\",\"',$_POST["groups"]).'\")';
echo '<pre>'; print_r($groups); echo '</pre>';
if (isset($_POST['cGrps'])) {
$res1 = shell_exec("powershell -InputFormat none -ExecutionPolicy ByPass -NoProfile -Command $ADJoinGroups $fName $lName $groups 2>&1");
echo $res1;
}
?>
Powershell 脚本如下所示:
###### Args ######
$fName = $args[0];
$lName = $args[1];
$groups = $args[2];
Write-output $groups;
有谁知道为什么会发生这种情况?并且,您有办法在 Powershell 中将其从
@("grp1","grp2")
恢复为 grp1 grp2
吗?
非常感谢:)
我运行的测试脚本是为了模拟原始脚本,其区别在于命令行字符串的
groups
部分用双引号括起来,组名称用单引号括起来。
<?php
$ADJoinGroups = "C:\data\Archives\Scripts\Powershell\AD_Joingrps.ps1";
$_POST["entity"]='Corporate Chief';
$_POST["description"]='Something...or...other';
$_POST["fName"]='John';
$_POST["lName"]='Smith';
$_POST['groups']=array( 'printusers', 'powerusers', 'cor-c-dc-telstar1', 'cor-c-dc-frontline' );
$entity = $_POST["entity"];
$fName = $_POST["fName"];
$lName = $_POST["lName"];
$desc = $_POST["description"];
$password = "#####";
# individual groups within single quotes
$groups=sprintf( "@('%s')", implode( "','", $_POST['groups'] ) );
# entire groups portion within double-quotes
$cmd=sprintf('powershell -InputFormat none -ExecutionPolicy ByPass -NoProfile -Command %s %s %s "%s" 2>&1', $ADJoinGroups, $fName, $lName, $groups );
$res=shell_exec( $cmd );
printf( '<pre>%s</pre>', print_r( $res,true ) );
?>
Powershell测试脚本:
function adUserGroups{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)][String] $fName,
[Parameter(Mandatory=$true)][String] $lName,
[Parameter(Mandatory=$true)][Array] $groups
)
Write-output $fName, $lName;
foreach( $group in $groups ){
write-output "Add to Group->$group"
}
}
adUserGroups -fName ($args[0]) -lName ($args[1]) -groups ($args[2])
浏览器中的输出:
John
Smith
Add to Group->printusers
Add to Group->powerusers
Add to Group->cor-c-dc-telstar1
Add to Group->cor-c-dc-frontline
谢谢@Abronsius 教授;)我的 $groups 周围的单引号成功了
shell_exec("powershell -InputFormat none -ExecutionPolicy ByPass -NoProfile -Command $ADJoinGroups $fName $lName '$groups' 2>&1");```