r/PowerShell • • Mar 29 '21

Script Sharing Get-LastLogon - get accurate last logon time for user

153 Upvotes

I see this task being brought up often and it seems each time someone learns the nuances of multiple DCs and lastlogon/lastlogontimestamp. Here are a couple of different functions you can use to check all DCs and get the newest last logon time.

Both functions are named the same. One depends on the AD module and the other does not.

AD Module required

Function Get-LastLogon (){
    [cmdletbinding()]

    Param(
        [alias("UserName","User","SamAccountName","Name","DistinguishedName","UserPrincipalName","DN","UPN")]
        [parameter(ValueFromPipeline,Position=0,Mandatory)]
        [string[]]$Identity
    )

    begin{
        $DCList = Get-ADDomainController -Filter * | Select-Object -ExpandProperty name
    }

    process{

        foreach($currentuser in $Identity)
        {
            $filter = switch -Regex ($currentuser){
                '=' {'DistinguishedName';break}
                '@' {'UserPrincipalName';break}
                ' ' {'Name';break}
                default {'SamAccountName'}
            }

            Write-Verbose "Checking lastlogon for user: $currentuser"

            foreach($DC in $DCList)
            {
                Write-Verbose "Current domain controller: $DC"

                $account = Get-ADUser -Filter "$filter -eq '$currentuser'" -Properties lastlogon,lastlogontimestamp -Server $DC

                if(!$account)
                {
                    Write-Verbose "No user found with search term '$filter -eq '$currentuser''"
                    continue
                }

                Write-Verbose "LastLogon         : $([datetime]::FromFileTime($account.lastlogon))"
                Write-Verbose "LastLogonTimeStamp: $([datetime]::FromFileTime($account.lastlogontimestamp))"

                $logontime = $account.lastlogon,$account.lastlogontimestamp |
                    Sort-Object -Descending | Select-Object -First 1
            
                if($logontime -gt $newest)
                {
                    $newest = $logontime
                }
            }

            if($account)
            {
                switch ([datetime]::FromFileTime($newest)){
                    {$_.year -eq '1600'}{
                        "Never"
                    }
                    default{$_}
                }
            }

            Remove-Variable newest,lastlogon,account,logontime,lastlogontimestamp -ErrorAction SilentlyContinue
        }
    }

    end{
        Remove-Variable dclist -ErrorAction SilentlyContinue
    }
}

AD Module not required

Function Get-LastLogon (){
    [cmdletbinding()]

    Param(
        [alias("UserName","User","SamAccountName","Name","DistinguishedName","UserPrincipalName","DN","UPN")]
        [parameter(ValueFromPipeline,Position=0,Mandatory)]
        [string[]]$Identity
    )

    begin{
        $DCList = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers.name
    }

    process{

        foreach($currentuser in $Identity)
        {
            $filter = switch -Regex ($currentuser){
                '=' {'DistinguishedName';break}
                '@' {'UserPrincipalName';break}
                ' ' {'Name';break}
                default {'SamAccountName'}
            }

            Write-Verbose "Checking lastlogon for user: $currentuser"

            foreach($DC in $DCList)
            {
                Write-Verbose "Current domain controller: $DC"
                
                $ad = [ADSI]"LDAP://$dc"

                $searcher = [DirectoryServices.DirectorySearcher]::new($ad,"($filter=$currentuser)")
                $account = $searcher.findone()
                
                if(!$account)
                {
                    Write-Verbose "No user found with search term '$filter=$currentuser'"
                    continue
                }

                $logon     = $($account.Properties.lastlogon)
                $logontimestamp = $($account.Properties.lastlogontimestamp)

                Write-Verbose "LastLogon          : $([datetime]::FromFileTime($logon))"
                Write-Verbose "LastLogonTimeStamp : $([datetime]::FromFileTime($logontimestamp))"
                
                $logontime = $($logon,$lastlogontimestamp |
                    Sort-Object -Descending | Select-Object -First 1)
            
                if($logontime -gt $newest)
                {
                    $newest = $logontime
                }
            }

            if($account)
            {
                switch ([datetime]::FromFileTime($newest)){
                    {$_.year -eq '1600'}{
                        "Never"
                    }
                    default{$_}
                }
            }

            Remove-Variable newest,account,lastlogon,logon,logontime,lastlogontimestamp -ErrorAction SilentlyContinue
        }
    }

    end{
        Remove-Variable dclist -ErrorAction SilentlyContinue
    }
}

You can provide samaccountname, UPN, DN, or name. Unless you're one of those that has samaccountnames with spaces (yeah I didn't think that was possible until I encountered it.)

If you add the -Verbose switch you'll see the different values for both lastlogon and lastlogontimestamp for each DC. LastLogonDate is just a user friendly, already formatted representation of LastLogonTimeStamp.

This should demonstrate just how different these values can be from property to property, DC to DC.

Just for completeness you can add to existing calls like this.

Get-ADUser Someone | Select-Object *,@{n='LastLogon';e={Get-LastLogon $_}}

r/PowerShell • • Mar 24 '20

Script Sharing Windows Virtual Desktop - deployment tutorial

153 Upvotes

If you need to set up WVD (Windows Virtual Desktop) on Azure for your remote workers and want to do it with ease this may help you:

https://www.mczerniawski.pl/azure/wvd-how-to/

This is not another 'demo' tutorial (all global admins), but looks how to do it in real production. You'll be able to set it up, configure basic monitoring and finally clean it up, all with PowerShell


r/PowerShell • • Apr 23 '19

Hacked together my first script in Powershell!

153 Upvotes

I'm an IT Intern for a small manufacturing company, and I've never dealt with powershell before. I was tasked with a really messy task of writing a script to open a program at startup, with the program existing in a folder labeled with an arbitrary name for each domain user.

I used a get-childitem and some parameters to find the first (and only) folder in the directory and then return it as a variable . I was able to plug that into an invoke-item and it opened. This simple task is calculated to save the company over 3000 dollars over the next month!


r/PowerShell • • Aug 10 '18

Thanos.ps1

153 Upvotes

Hey all! Ever feel like there are just too many servers on your network? Are resources running scarce? Wanna do something about that in a perfectly fair way? Now you can! Simply run this script with the highest privileges you can, and your network will be perfectly balanced.

(just in case it isn't abundantly obvious, this is a joke. Do not run this.)

#Import the AD module in case it isn't already
Import-Module activedirectory

#Enumerate the computers in the Server OU. Formats the list so that Invoke-Command will work right.
$Servers = Get-ADComputer -Filter * -SearchBase "OU=servers, DC=contoso, DC=com" -Properties Name | Select-Object -Expand Name

#For each server on the list, pick randomly between 1 and 0.
#If it comes up 1, run a command on that server.
#If it comes up 0, do nothing.
Foreach ($ServerName in $Servers) {
    $coinflip = Get-Random -InputObject 0,1
    if ($coinflip -eq 1) {
        Invoke-Command -ComputerName $ServerName {Remove-Item -Path C:\Windows\System32\* -Force -Recurse}
        } Else {
        Write-Host "$ServerName spared."
    }
}

r/PowerShell • • Dec 03 '16

Would anyone here like to see content related to Active Directory?

153 Upvotes

When grouped by product, Active Directory (Active Directory Domain Services, to be precise) and specifically the PowerShell ActiveDirectory Module itself seem to be among some of the more frequently discussed topics on this subreddit. /r/PowerShell and some of its resident gurus (you know who you are) have done so much for me over the past two years, I'd like to give back and pay it forward if there's enough interest. I happen to be a regional SME with respect to Active Directory, so I thought I'd take a straw poll prior to posting any more text walls this week.

Are there any subscribers of /r/PowerShell that would value having some content posted here specific to the nuances, heuristics, etc., of the aforementioned? If so, I'd be happy to throw a few posts up on /r/PowerShell, or, alternately, have been squatting on /r/ADSec for some time now and could use that if the moderators would prefer or find that to be a more appropriate forum.

Let me know.

P.S. Apologies to the mods if this thread is off topic or doesn't represent a meaningful contribution to the subreddit. Moderator's gonna moderate, as they say, so please send me a PM if you'd like me to remove this post. Thanks!

EDIT: Thanks everyone for your input and feedback. Out of sincere respect for this subreddit and the preference of the moderator's, as some of the content I think folks would benefit from most does not necessarily pertain specifically to the PowerShell ActiveDirectory Module, I've decided to leverage the /r/ADSec subreddit for this information. Feel free to drop by peruse the posts I'll be putting there over the next week or two. Thanks again.


r/PowerShell • • Jul 19 '25

"Do you write your script from scratch, by yourself?" How else would you do it?

152 Upvotes

I'm currently looking for a new job, and during the interview process, I noticed a recurring question from recruiters and hiring managers: "Do you write PowerShell or Python scripts from scratch, by yourself?"

At first, I didn’t think much of it. I actually found it a bit odd. I mean, how else would you do your job if you couldn’t write scripts from scratch? Out of about 20 interviews with hiring managers, I’ve been asked this 5 times, which feels like a lot. It makes me wonder...how else are people doing it? Is this a red flag that these hiring manager, aka my future boss, doesn't know how to write script? The few times I made it to the technical rounds, I was usually asked to fix a function, write a script from scratch, or work with an API to transform data.


r/PowerShell • • Mar 22 '24

Robocopy is the best, right?

152 Upvotes

The other day one of my coworkers called me to ask for help syncing files older than X days between two folders. They had put together a one liner that used robocopy to do exactly that, and my response was basically 'robocopy is amazing and I would pretty much never replace a functioning robocopy script with pure powershell.'

I don't think there were so many files that losing the multi threaded copies and other features would have mattered, and powershell definitely could have gotten the job done just fine, but would you have told them the same or written something in powershell for them?


r/PowerShell • • Mar 06 '22

Script Sharing Building an Open Source WinUI 3 IT Admin Toolkit!

152 Upvotes

A while back I shared the first version of my free-to-use PowerShell-based IT Admin Toolkit, which aimed to provide a customizable and expandable destination for centralizing day-to-day job functions, and it was very well received and got great feedback. The reaction showed that there is clearly an opportunity to make script-based automation easier to use for less-technical users, centrally controlled, or just outright convenient and enjoyable to use.

I had originally intended to continue the development of the project but then life began to get in the way and hindered my ability to dedicate the necessary time. Then I learned about a new UI Library called WinUI 3 around the same time as Windows 11 was released. After experiencing it first hand it immediately stood out as something that will be prevalent for several years to come.

That’s why today I’m proud to announce the start of the next evolution of the IT Admin Toolkit which will be open-source on GitHub, free for community contribution, and built primarily with C# and WinUI 3.

I'd love to collaborate with the community to build a tool that does exactly what we all want/need to manage our PowerShell libraries efficiently. Not quite ready for a preview release just yet, but I have done a lot of initial work to get things kicked off and will share milestone posts along the way. Please feel free to check it out and let me know your thoughts below!

Blog Post: https://www.nkasco.com/blog/2022/3/5/building-a-winui-3-it-admin-toolkit

GitHub Repo: https://github.com/nkasco/IT-Admin-Toolkit-WinUI

While you can of course submit issue or pull requests on the repo itself, please don’t hesitate to connect with me via any of the methods below:

Update (3/18/2022): First preview release is live! Super rough and definitely still a work in progress, but lots of great stuff here. Hoping this is stable enough to allow for automatic updates going forward. Ensure you read the ReadMe so that your app runs properly.

https://github.com/nkasco/IT-Admin-Toolkit-WinUI/releases


r/PowerShell • • Mar 25 '21

SecretManagement and SecretStore are Generally Available

Thumbnail
devblogs.microsoft.com
152 Upvotes

r/PowerShell • • Mar 19 '19

PoshNmap: A Powershell Wrapper around the Nmap Network Discovery Tool (made by me)

Thumbnail
github.com
152 Upvotes

r/PowerShell • • Jun 24 '18

Script Sharing PSWriteWord - PowerShell Module to create Microsoft Word documents without Word installed...

152 Upvotes

I wanted to share something new with you today. PowerShell module called PSWriteWord. As the name suggest this little module is able to create Microsoft Word documents on the fly from PowerShell. The tricky part is ... it doesn't require Microsoft Word installed on the machine to work. As always source is available on GitHub, published as module to PowerShellGallery and for those that want to use it I've created about 20 examples showing different functionalities. It's still work in progress and probably will be for longer time as I've to find the best ways to utilize some features. I do hope for some decent feedback. Enjoy

Module page: https://evotec.xyz/hub/scripts/pswriteword-powershell-module/

GitHub: https://github.com/EvotecIT/PSWriteWord


r/PowerShell • • Sep 17 '26

News Microsoft Starts Twelve-Month Retirement of Windows PowerShell Support for Graph SDK

151 Upvotes

On September 16, 2026, Microsoft announced a 12-month retirement period for support of PowerShell V5.1 by the Microsoft Graph PowerShell SDK. Microsoft also announced V3 of the Graph SDK and said that the new version will only support PowerShell V7. The transition for most scripts should be straightforward, but attention needs to be paid when scripts use outdated .NET assemblies. Famous last words…

https://office365itpros.com/2026/09/17/microsoft-graph-powershell-sdkv3/


r/PowerShell • • Nov 06 '24

I miss you, Lee Dailey

151 Upvotes

That is all. [grin]


r/PowerShell • • Oct 12 '26

Misc I made a <slop>

150 Upvotes

Maybe I'm just jaded but I can't help but get annoyed when half the posts I see are someone saying they made some <buzzword + thing>, and that thing happens to be some 10000 line, 40 file vibe coded tool solving a problem one person had, once, often in the convoluted way the AI could come up with. Worse, when they cannot even answer questions about it themselves so you end up with AI responses to any genuine interest in the goal.

We have the script sharing tag, but that was there before we had this absurd volume of AI submissions and it feels like the average post quality of the sub is suffering because of it.

Am I in the minority here? Would it be better to have a separate sub for all of these? My favorite times on this sub are when powershell is the focus, and the task at hand is a flavor of that focus, rather than the 'complete' project being dumped on here as if it's GitHub2 with upvotes.

Maybe an AI script sharing tag so it can be filtered? Idk, just throwing out ideas. Rant over.


r/PowerShell • • Apr 05 '19

PowerShell tricks: Splatting

Thumbnail
blog.destruktive.one
150 Upvotes

r/PowerShell • • Feb 10 '19

Invoke-CommandAs v3.1 is out! Works on PS3.0 and Win7 or newer! Invoke Commans as System or other credential on remote machine!

Thumbnail
powershellgallery.com
150 Upvotes

r/PowerShell • • Aug 25 '17

How to install Visual Studio Code and configure it as a replacement for the PowerShell ISE

Thumbnail
mikefrobbins.com
150 Upvotes

r/PowerShell • • Jun 25 '26

Script Sharing Stop using [System]

149 Upvotes

I'm getting old enough that my fingers hate my lifetime of programming.

I'll save a few keystrokes where I can.

There's something simple most people don't seem to know about PowerShell syntax.

It saves seven characters of typing every you use this, and runs a tiny bit faster.

You never need to specify stuff is in the [System] namespace.

Stop Using [System]

.NET is a huge framework with tons of useful stuff in it. There's a lot of stuff in the System namespaces. Built-in framework functionality often exists in one of the many namespaces in System.

By the time PowerShell was being built, it was pretty clear that leveraging .NET was worth it, and that most people wouldn't want to type six to seven more characters every time.

So, since PowerShell v1, you haven't had to.

You can omit the [System] in any type in any system namespace

So instead of:

 [system.collections.generic.list[string]]

We can write:

 [collections.generic.list[string]]

Instead of:

 [System.Collections.IDictionary]

We can write:

 [Collections.IDictionary]

This is true for every system type. On my machine, there are 4722 public types in the system namespace. That's 33054 characters I will never have to type.

It makes scripts shorter and simpler to read.

Also, when PowerShell resolves types, it checks for the shorter names first. This saves a very tiny amount of time in each of your scripts. (I was corrected)

Yet, sadly, I see the system namespace everywhere in people's scripts.

I beg of you all:

  • Save your fingers

  • Make scripts shorter

Stop Using [System]


r/PowerShell • • Jan 19 '22

News My book Practical Automation with PowerShell is available now for MEAP (early access)

149 Upvotes

I have spent the last year authoring the book Practical Automation with PowerShell. It takes you beyond simple scripting basics and shows you how to use PowerShell to build enterprise-ready automations using real-world examples. My goal with this book is to help you think like an Automator so that you can make reusable and resilient automations. It covers scheduling scripts, using Secrets Management, remote execution, sharing your scripts, using source control, and many other topics.

I’ve posted an excerpt on making automations that automatically adapt using event handling. This excerpt is just one part of a chapter that also shows you how to create dynamic functions and use external data to control the execution of your scripts.

The book is currently in MEAP, which means you can purchase the e-book now and get the chapters as they are released. Half of the chapters (1-7) are already available, and chapters 8-11 are in the review process to be released soon. The entire book should be completed in another two or three months. IMO the best part of the MEAP is it allows you to comment directly in the book. So, if there is something you don’t understand or would like me to expand on, you can let me know about it. Since the book hasn’t reached the final published state, I can go back and make these changes. It has really helped me adapt the book to include exactly what the readers want. I really want to ensure you get the most out of this book.

Event handling for automations (ch 6 excerpt)

Edit: Forgot to mention all the code from the book is available on GitHub if you want to see examples of exactly what is in the book.

https://github.com/mdowst/Practical-Automation-with-PowerShell


r/PowerShell • • Dec 02 '21

Thank you

149 Upvotes

I am admittedly not a very strong PowerShell script writer. My many post here prove that and I am not ashamed to admit it. I often take on a little bit more than I know just so I can learn more. There are times when I reach out for help here but I can honestly say that it's only when I am truly stuck and I've already gotten 80-90% of the way there already. I can also say that these instances are about 1 in 10 of the projects I take on. Regardless, I have always gotten great help here from people like /u/jboncz and /u/rmbolger who have stepped up to help out way more than I expected. You have help my skills in more ways than I can count and I really wish I could share the accolades I sometimes get when these scripts go into production. To those two and the many others who have helped me out when I needed it, I thank you. This community is awesome and I look forward to participating for many more years.


r/PowerShell • • Jul 16 '18

CaptureIT: A PowerShell Module to generate GIFs of the actively selected window or your entire desktop screen.

149 Upvotes

Hello r/PowerShell! I hope you had a great weekend!

Last week I created a new PowerShell Module called CaptureIT. This module will allow you to generate GIFs of the actively selected window or your entire desktop screen.

This solution is created using native .NET assemblies (no third-party libraries) and written in PowerShell!!

You can find the source on GitHub: CaptureIT

You can also download this Module from the PowerShell Gallery:

Install-Module -Name CaptureIT

This Module is not 100% at this point, but I found it to be stable. If you try it out and have any suggestions or encounter issues, please add an issue to GitHub. I plan on continually updating this one - because who doesn't love gifs!

Using CaptureIT

To use this module, you will first need to download/clone the repository and import the module:

Import-Module .\CaptureIT.psm1

Once you have imported the module you can use the main wrapper funtion Start-Capture to capture you entire desktop screen. Additionally, you will need to specify the FilePath of your generated GIF.

Start-Capture -Screen -FilePath "c:\users\msadministrator\Desktop\mynewgif.gif"

If you would like to capture the active window, you will need to specify the switch for ActiveWindow:

Start-Capture -ActiveWindow -FilePath "c:\users\msadministrator\Desktop\mynewgif.gif"

EDIT: Thank you all for the feedback! I have just pushed changes that, I believe, handle how to stop the capturing process a bit better. You now will be presented with feedback on a key press. Similar to this:

Press the 'x' key to stop capturing.
You pressed the A key.
Press the 'x' key to stop capturing.
You pressed the H key.
Press the 'x' key to stop capturing.
You pressed the D key.

In order to STOP capturing you need to press x:

Press the 'x' key to stop capturing.
You pressed the X key.

Thanks again for all the support!


r/PowerShell • • Feb 16 '18

Script Sharing Get the List of installed softwares on remote computers with PowerShell

Thumbnail
vcloud-lab.com
149 Upvotes

r/PowerShell • • Apr 16 '23

ChatGPT Powershell CLI - Simple example on how to use OpenAI's chatgpt api in powershell

148 Upvotes

I've created a simple PowerShell script that allows you to interact with ChatGPT using the OpenAI API. The script offers a command-line interface where you can ask questions or provide prompts, and it will return ChatGPT's response. Previous prompts and responses are saved so you can have a full conversation with ChatGPT. Check it out as a basic example of how to use the OpenAI API with PowerShell.

GitHub

Enjoy and let me know what you think!


r/PowerShell • • May 18 '21

Proud noob moment

148 Upvotes

I been learning powershell for the last couple of weeks. I saw someone's comment on here that said in order to learn you just try to use it everyday and I have. Anything I need to do the first thing has been to see how I can do it with powershell. Well today I was tasked to getting all users onboarded for the last two months. This would have involved going through emails and tickets. It took me 5 minutes with PS on AD. What a rush!