Create your first PowerShell function

For those who are starting their journey with PowerShell I prepared today short article describing how to create first simple function. To makes things a little bit complicated I added if/else conditions to give better functionality to our script. Function name is called Get-Sessions and it will check for Active Directory users sessions and status on some particular server.


I used if/else conditions to make sure that person who use this function will be forced to use it correctly. In case of wrong usage warning message will show up:

“USAGE: Get-Sessions [-Server]”


For checking sessions on server remotely I used “qwinsta command with $server parameter. For each session names I also checked if account is an AD user( get-aduser -Identity $query.SESSIONNAME ). In my case user name was under sessioname property ( $query.SESSIONNAME ) – you can test it and check it in your own environment, it might be also stored under username property ( $query.USERNAME ).


Of course you can use easier method to get all of those information but for purpose of this article I used qwinsta:

Get-RDUserSession | select username,sessionstate,createtime,DisconnectTime | sort sessionstate  | ft -autosize 


Function Get-Sessions{

    param($Server = ”blank”)

        If ($Server -eq “blank”)
            Write-Warning “USAGE: Get-Sessions [-Server]”
            Write-Host "`nSessions on $Server :`n" -ForegroundColor Yellow

            $queries = (qwinsta /server:$Server | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv)

            ForEach($query in $queries)
                $RDPUser = $query.USERNAME
                $Session = $query.SESSIONNAME
                $id = $
                If (Get-ADUser -Identity $query.SESSIONNAME )
                    Write-Host $id - User : $Session


Get-Sessions DC01

Query Session / Qwinsta

Display information about user sessions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.