PowerShell for Windows Admins

Jan 18 2012   1:29PM GMT

Running a function



Posted by: Richard Siddaway
Tags:
PowerShell

Most of my scripts end up being functions because I will eventually combine them into modules

My recent script

function get-logedonuser {                        
param (                        
 [string]$computername = $env:COMPUTERNAME                        
)                        
Get-WmiObject -Class Win32_LogonSession -ComputerName $computername |                        
foreach {                        
 $data = $_                        
                        
 $id = $data.__RELPATH -replace """", "'"                        
 $q = "ASSOCIATORS OF {$id} WHERE ResultClass = Win32_Account"                        
 Get-WmiObject -ComputerName $computername -Query $q |                        
 select @{N="User";E={$($_.Caption)}},                         
 @{N="LogonTime";E={$data.ConvertToDateTime($data.StartTime)}}                        
}                        
}

Prompted a comment about how could you run this script.

First off I would save it to a file – get-logedonuser.ps1

You can then either

Open PowerShell Integrated Scripting Environment (ISE) and the open the file. if you run the file the function is added into memory and you can run it as get-logedonuser

 

OR

open the PowerShell console, change to the folder where you saved the file, and run . ./get-logedonuser.ps1

This “dot sources” the script and leaves the function in memory. Then run get-logedonuser as before

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: