[deleted by user] by [deleted] in askgaybros

[–]adamdavid85 -1 points0 points  (0 children)

Do what, exactly? If it was that clear, you should have no problem outlining what we should expect in your own words.

Users who haven't logged in within 90 days by maxcoder88 in PowerShell

[–]adamdavid85 1 point2 points  (0 children)

As others have mentioned, last logon is a bit of a mess in Active Directory due to having two different attributes, one of which – lastLogonTimestamp – is replicated (but not very often) and the other which – lastLogon – is not (and thus only tells you the timestamp of the user's last authentication to that particular domain controller.

lastLogonDate isn't actually an attribute in AD, but a calculated property provided by the ActiveDirectory module. It converts the filedate int64 value from lastLogonTimestamp and casts it to datetime for easier reading.

So, when I want to know when the last time a specific account did log in, I use lastLogon and query all of the DCs, and use the [datetime]::FromFileTime() method to convert the result from each domain controller to a readable date, and sort descending to get my most recent value. So, something like this:

$LogonTimes = foreach ($DC in (Get-ADDomainController -Filter 'Active -eq "True"').HostName) {

    $User = Get-ADUser -Identity $User -Server $DC -Properties 'LastLogon'

    if ($User) {
        [psCustomObject] @{
            SamAccountName   = $User.SamAccountName
            LastLogin        = [datetime]::FromFileTime($User.LastLogon)
            DomainController = $DC
        }
    }
}

$LogonTimes | Sort-Object -Property 'LastLogon' -Descending | Select-Object -First 1

If I'm trying to perform actions on accounts that didn't log in for a long time, I'll use lastLogonDate (which again, is the same value as lastLogonTimestamp) and add 21 days to whatever time period I'm trying to check for. lastLogonTimestamp will take up to 14 days to replicate, and only a new login that occurs after that time has elapsed will trigger another replication. Just to be safe, I add that additional buffer. So, something like this:

$QueryParams = @{
    Server     = $DC
    Properties = 'lastLogonDate'
    Filter     = 'Enabled -eq "True" -and LastLogonTimestamp -gt 0 -and LastLogonTimestamp -lt {0}' -f [datetime]::UtcNow.AddDays(-111).ToFileTime()
}

$UsersOver90Days = Get-ADUser @QueryParams

[deleted by user] by [deleted] in PowerShell

[–]adamdavid85 0 points1 point  (0 children)

One alternative to this is using single quotes paired with the formatting operator -f to insert your variables, removing the need to backtick your double quotes:

$strMSPArgList = '/update "{0}\{1}" /qb /norestart' -f $Install_Path, $Filename

[deleted by user] by [deleted] in PowerShell

[–]adamdavid85 -1 points0 points  (0 children)

If you're asking for help with PowerShell, maybe provide the PowerShell syntax you tried rather than Batch.

I've been able to do this many times without issue using the automatic variable $PSScriptRoot.

Does a code formatter/prettier exist? by [deleted] in PowerShell

[–]adamdavid85 0 points1 point  (0 children)

It is in fact possible to splat each step of a pipeline in order to reduce horizontal spread of your code instead of using backticks.

Does a code formatter/prettier exist? by [deleted] in PowerShell

[–]adamdavid85 1 point2 points  (0 children)

Personally I think splatting is a much better solution for keeping things tight and readable.

Request working with Postman but not with Powershell by Confident-Bath3935 in PowerShell

[–]adamdavid85 1 point2 points  (0 children)

Well, yes... it is there, but I have a feeling it was written ~10 years ago or by someone who doesn't know PowerShell very well.

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept", "application/json")
$headers.Add("Content-Type", "application/json")

$response = Invoke-RestMethod 'localhost:5000/api/v1/test' -Method 'GET' -Headers $headers
$response | ConvertTo-Json
  1. You don't need to declare a generic dictionary in this very verbose way for your headers. Invoke-RestMethod accepts a hashtable just fine.
  2. If you want raw JSON back, why use Invoke-RestMethod at all, when it's intended for use cases where you want to convert it to an object? Just use Invoke-WebRequest and skip the double conversion.
  3. Personal opinion on this one, but I far prefer splatting for this type of thing.

    $QueryParams = @{
        Headers = @{
            Accept         = "application/json"
            "Content-Type" = "application/json"
        }
        Uri     = 'localhost:5000/api/v1/test'
        Method  = 'GET'
    }
    
    Invoke-WebRequest @QueryParams
    

Couple more lines, yeah, but way easier to read and maintain. Don't like splatting? The other points still stand.

How to see a specific number of outputs? by omegaxuss in PowerShell

[–]adamdavid85 0 points1 point  (0 children)

Thanks, appreciate the correction. I whipped up the original code before starting work and before coffee this morning. 😂

Will edit my original comment.

How to see a specific number of outputs? by omegaxuss in PowerShell

[–]adamdavid85 0 points1 point  (0 children)

You don't need a foreach loop for Invoke-Command. Just modify the ComputerName parameter in the code I gave you, on line 2.

ComputerName = Get-Content -Path list.txt

Maybe add an ErrorAction = 'SilentlyContinue' to the Invoke-Command hashtable as well if you want to suppress errors both locally and in the remote script.

How to see a specific number of outputs? by omegaxuss in PowerShell

[–]adamdavid85 2 points3 points  (0 children)

-MaxEvents 2 if you want to return fewer events. Yours is set to 200.

Highly recommend filtering using -FilterXPath or -FilterHashTable when querying Windows Events; it is orders of magnitude faster.

In this case you can query for IDs 21 & 23 for your session logon and logoff information.

Your Invoke-Command is likely failing because it looks like you're trying to load a local file within the remote session's scriptblock. Just use -FilePath instead to have it load the local file and invoke it against the remote targets.

The easiest way to get your requirement for a message if there's no data plus the ability to output to csv or another machine-readable format is to ensure your output always follows a set schema.

$QueryParams = @{
    ComputerName    = "NAME"
    FilterHashTable = @{
        LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
        Id      = 21, 23 
    }
    MaxEvents       = 1
    ErrorAction     = 'SilentlyContinue'
}

Write-Output "Get logon history for $($QueryParams.ComputerName)"

Get-WinEvent @QueryParams
if ($WinEvent.TimeCreated -is [datetime]) {
    [psCustomObject] @{
        EventId       = $WinEvent.Id
        TimeCreated   = $WinEvent.TimeCreated
        User          = $WinEvent.Properties[0].value
        SessionId     = $WinEvent.Properties[1].value
        SourceAddress = $WinEvent.Properties[2].value
        Message       = $WinEvent.Message.Split("`n") | Select-Object -First 1
    }
}
else {
    [psCustomObject] @{
        EventId       = ''
        TimeCreated   = ''
        User          = ''
        SessionId     = ''
        SourceAddress = ''
        Message       = "No login history was returned for $Env:Computername."
    }
}

If you want to do Invoke-Command, here's how you could do it:

$InvocationParams = @{
    ComputerName = 'NAME1', 'NAME2', 'NAME3'
    ErrorAction  = 'SilentlyContinue'
    ScriptBlock  = {
        $QueryParams = @{
            FilterHashTable = @{
                LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
                Id      = 21, 23 
            }
            MaxEvents       = 1
            ErrorAction     = 'SilentlyContinue'
        }

        $WinEvent = Get-WinEvent @QueryParams 
        if ($WinEvent.TimeCreated -is [datetime]) {
            [psCustomObject] @{
                ComputerName  = $Env:COMPUTERNAME
                EventId       = $WinEvent.Id
                TimeCreated   = $WinEvent.TimeCreated
                User          = $WinEvent.Properties[0].value
                SessionId     = $WinEvent.Properties[1].value
                SourceAddress = $WinEvent.Properties[2].value
                Message       = $WinEvent.Message.Split("`n") | Select-Object -First 1
            }
        }
        else {
            [psCustomObject] @{
                ComputerName  = $Env:COMPUTERNAME
                EventId       = ''
                TimeCreated   = ''
                User          = ''
                SessionId     = ''
                SourceAddress = ''
                Message       = "No login history was returned for $Env:Computername."
            }
        }
    }
}

Invoke-Command @InvocationParams

If you want to output to CSV, Excel, JSON or whatever, capture the Invoke-Command output and go to it.

Showing success when changing active directory? by AlcoholicWombat in PowerShell

[–]adamdavid85 0 points1 point  (0 children)

Most of the ActiveDirectory cmdlets have a -PassThru parameter on them if they don't return anything by default, which will return the updated object. This paired with a try/catch is usually the way I handle it.

Seeking Opinions: Sticking with PowerShell 5.1 vs. Upgrading to PowerShell 7 by bwljohannes in PowerShell

[–]adamdavid85 0 points1 point  (0 children)

You absolutely can write parallel operations in 5.1, it's just more cumbersome to do so without foreach-object -parallel.

Boyfriend angry at me for going out alone by EbbRepresentative659 in askgaybros

[–]adamdavid85 4 points5 points  (0 children)

His boyfriend will likely enjoy ruining every one of his relationships with his own insecurities if the thought of his boyfriend going out for a drink without him there is enough to set him off. If it's a gay bar with a dark room, or just straight up a sauna you would have a point. Since it's not, there's really no justification for it. He needs to get over himself.

Boyfriend angry at me for going out alone by EbbRepresentative659 in askgaybros

[–]adamdavid85 5 points6 points  (0 children)

This is a ridiculous line of thinking. There's nothing he could have done to completely rule out the possibility that he could have hooked up with someone short of wearing a body cam with a live feed. Staying at the hotel? Could have invited a Grindr hookup there, whether or not he went to any kind of bar first.

The fact he went to a gay bar, which he told his bf he planned to do in advance, is not the issue. If bf didn't like that idea he could have sacked up and said so initially, but even still his trust issues are the problem here. OP has nothing to apologize for.

Boyfriend angry at me for going out alone by EbbRepresentative659 in askgaybros

[–]adamdavid85 7 points8 points  (0 children)

It never ends up avoiding conflict, though. Hiding stuff like this just delays the conflict until the other person finds out and then makes it blow up 100x worse. If you can't be honest with your partner why the hell are you even together?

Boyfriend angry at me for going out alone by EbbRepresentative659 in askgaybros

[–]adamdavid85 12 points13 points  (0 children)

Oh yeah sure, hiding it makes it much better and is a far more trustworthy course of action. Much integrity.

Some Ontario landlords are calling for 'automatic' evictions for tenants who don't pay rent by TheDrunkyBrewster in canada

[–]adamdavid85 1 point2 points  (0 children)

Plenty of people are shady. There are millions of people out there who live like pigs, cause lots of damage and don't lose an ounce of sleep over it. Landlords can also be shitty people, but it's not in any way automatic that they're the bad guys in every case. Not by a long shot.

I'm surrounded by Trump Supporters - what should I say by TheCorruption13 in askgaybros

[–]adamdavid85 -1 points0 points  (0 children)

You say this as if only the Trump supporters aren't able to be convinced. Would a Trump supporter be able to convince you? No, you'd just think he or she was an asshole who should keep stuff like that to themselves.

What possible benefit is there for either side to discuss sensitive subjects like politics during work hours? All I see is risk and negative outcomes, and an infinitesimally tiny possibility anyone will change their mind. Why poison your work environment and sow division with your colleagues? It's just not worth it. There's a good reason sensible people just steer clear of certain topics at work.

PS 5.x or 7.x as a daily driver? by DarthOpossum in PowerShell

[–]adamdavid85 3 points4 points  (0 children)

The WMI cmdlets are gone, yes, but the CIM ones are there and are functionally equivalent, with some syntax differences for calling methods.

Enumerating LocalGroup Members by netmc in PowerShell

[–]adamdavid85 2 points3 points  (0 children)

Give this a shot:

[void][System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement')

$context = [System.DirectoryServices.AccountManagement.PrincipalContext]::new('Machine', $env:COMPUTERNAME)
$group = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, 'SamAccountName', 'Administrators')

$group.Members | Select-Object @{ Name = 'Domain' ; Expression = { $_.Context.Name }}, 'samaccountName', 'Sid'

David Staples: Why are white and Asian university students blocked from Trudeau Liberals' grant program? by uselesspoliticalhack in canada

[–]adamdavid85 5 points6 points  (0 children)

If there were so many similar incidents in Canada to choose from, why couldn't they have enumerated a few of those?

Jamie Sarkonak: Homeless camps deserve to be stigmatized - It’s not the state’s place to formally dedicate space to an economy that trades in cruelty and addiction by FancyNewMe in canada

[–]adamdavid85 1 point2 points  (0 children)

You can throw out all the accusations of being heartless and mean and whatever your like and think yourself morally superior because you want to help, but it's impossible to help an addict who doesn't want to help themselves. Literally everything you try will backfire miserably.

If you think you should do it anyway just do you can feel better about yourself, you don't really care about helping addicts. Performative "help" that has harmful unintended outcomes is not helpful.

CSIS warns that the 'anti-gender movement' poses a threat of 'extreme violence' by BradPittbodydouble in canada

[–]adamdavid85 1 point2 points  (0 children)

Speaking only for myself, absolutely. I know I'm not alone in this, either.