-2

When I execute command it shows error $sessionId is not defined and when I defined $sessionId =''; then it show error:

undefine variable $_

While this command is perfectly running in powershell. Please guide me.

shell_exec("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -NoProfile -InputFormat none -command $sessionId = ((quser /server:DC | Where-Object { $_ -match $userName }) -split ' +')[2]< NUL");
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
Mohd Atiq
  • 151
  • 1
  • 13
  • 2
    Is `$_` a powershell specific and not a PHP variable? If yes, then you need to escape it since `$_` will be counted as a PHP variable inside a double quoted string. Try `\$_`. – M. Eriksson Apr 19 '19 at 09:43
  • $_ is powershell specific. Sir I tried \$_ but doesn't work. – Mohd Atiq Apr 19 '19 at 09:49
  • https://stackoverflow.com/questions/28399983/execute-powershell-command-via-php – pearl Apr 19 '19 at 10:13

1 Answers1

0

Note, I can't get your Powershell snippet to work. When I run it, the shell gets hung up on the less-than "NUL" snippet (< NUL).

Powershell and PHP support string interpolation in double-quoted strings. From the shell_exec call, I'd think the variables I see (e.g., $sessionId, $userName, and $_) are PHP variables being interpolated, hence the undefined error. I'm not sure if that's what you want.

It looks like you're trying to get a session identifier from a username. You might want to try something like...

$machineName = 'myComputer';
$userName = 'me';
$command = sprintf("quser /server:%s | findstr %s", $machineName, $userName);
$session = shell_exec($command);
$session_id = preg_split('/ +/', $session, 0)[3];
print($session_id);

I'm using sprintf() to generate the shell command because its interpolation safe. And, in this example, I'm ONLY using shell to return the user's session. I'm doing everything else in PHP. Lastly, I'd factor Powershell out of this. I love Powershell, but it's only going to make things more complicated.

Adam
  • 3,891
  • 3
  • 19
  • 42