1

I am looking to run a script on a remote machine using an automation tool that runs the scripts in the system context.

What I have so far:

$userId = Get-Process -IncludeUserName explorer | % username | sort Username -Unique
Write-Host $userid.ToLower()

Results:

Get-Process : A parameter cannot be found that matches parameter name
'IncludeUserName'.
At line:1 char:39
+ $userId = Get-Process -IncludeUserName <<<<  explorer | % username | sort Username -Unique
    + CategoryInfo          : InvalidArgument: (:) [Get-Process], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetProcessCommand

ToLower : You cannot call a method on a null-valued expression.
At line:2 char:27
+ Write-Host $userid.ToLower <<<< ()
    + CategoryInfo          : InvalidOperation: (ToLower:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Any ideas how to help this script? Or the cause of the errors?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 2
    I'd suspect you're using PowerShell v3 or older. Apparently the parameter `-IncludeUserName` was [introduced with PowerShell v4](http://mikefrobbins.com/2013/06/27/powershell-version-4-new-feature-a-username-property-has-been-added-to-get-process-output-objects/). – Ansgar Wiechers May 02 '17 at 20:21
  • 3
    If you can't upgrade to PowerShell v4 or newer use [WMI](http://stackoverflow.com/a/32018396/1630171) to work around the issue. – Ansgar Wiechers May 02 '17 at 20:28

2 Answers2

2

The error says it all; the switch -IncludeUserName is not available on your computer. That's because it requires PowerShell 4.0 or above like Ansgar mentioned.

One solution is to install the latest Windows Mangement Framework (WMF) which includes the latest version of PowerShell.

You can also use the WMI-class Win32_Process to get the user and/or domain by calling the object's GetOwner()-method. Ex:

Get-WmiObject -Class Win32_Process -Filter "Name = 'explorer.exe'" |
ForEach-Object { $_.GetOwner() | % { "$($_.Domain)\$($_.User)" } } |
Sort-Object -Unique
Frode F.
  • 52,376
  • 9
  • 98
  • 114
0

the following script might help you. I'm not completely certain if the invoked command will get the remote logged in user, because I'm not on a work computer right now but it came from the internet so it must be true.

$Computers = (Get-Content "\\<sharedrive\<directory>\Computers.txt)

Foreach ($Computer in $Computers){ `
Invoke-Command -ComputerName $Computer -ScriptBlock `
{Get-WMIObject -Class Win32_ComputerSystem).Username} `
}
6ark
  • 34
  • 5