Running a function
Posted by: Richard Siddaway
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



You must be logged-in to post a comment. Log-in/Register