Home > Net >  How to avoid PowerShell command unrecognized term error
How to avoid PowerShell command unrecognized term error

Time:11-19

I want to run the command below to find the user session ID of a user and print it, and the command is the following:

$uid = Get-RDUserSession | Where-Object -filter {$_.UserName -eq 'pedro.vieira'} | select -ExpandProperty UnifiedSessionID; $uid

If I open powershell as Administrator, runs exactly as intended, yet if I open powershell without admin permissions, I get an error saying I should be in an elevated mode, which is expect.

However, for a specific motive, I want exactly for that to happen, so I'm trying the same command but prefixing it with Start-Process -Wait -PassThru -Verb RunAs powershell, like this:

Start-Process -Wait -PassThru -Verb RunAs powershell "$uid = Get-RDUserSession | Where-Object -filter {$_.UserName -eq 'pedro.vieira'} | select -ExpandProperty UnifiedSessionID; $uid; Start-Sleep -Seconds 5" 

Yet I get an error stating:

=: The term '=' is not recognized as the name of a cmdlet, function, script file, or operable program

I've tried escaping the dollar sign before the variable assignment but then I get an error stating that now the \ character is the one not recognized.

When I try a simpler command without variables, like the one below it works perfectly:

Start-Process -Wait -PassThru -Verb RunAs powershell "Get-RDUserSession"

What am I doing wrong?

CodePudding user response:

You can use Write-Output with -OutVariable to get the username to a string variable. Try something like:

Start-Process -Wait -PassThru -Verb RunAs powershell 'Write-Output pedro.vieira -OutVariable user; $uid = Get-RDUserSession | Where-Object -filter {$_.UserName -eq $user} | select -ExpandProperty UnifiedSessionID; $uid; Start-Sleep -Seconds 5'"
  • Related