-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");
3
  • 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 \$_. Commented Apr 19, 2019 at 9:43
  • $_ is powershell specific. Sir I tried \$_ but doesn't work. Commented Apr 19, 2019 at 9:49
  • stackoverflow.com/questions/28399983/… Commented Apr 19, 2019 at 10:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.