Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Friday, 22 April 2022

How to find the last interactive logons in Windows using PowerShell

Use the following powershell script to find the last users to login to a box since a given date, in this case the 21st April 2022 at 12pm until midnight on the 22nd April 2022 :-

  Get-WinEvent -FilterHashtable @{logname='Security'; id=4624; StartTime="2022-04-21 12:00"; EndTime="2022-04-22 00:00"} -MaxEvents 5000 | Where-Object {($_.Message -like '*Logon Type: 10*')} | select -Property @{Name = 'Info'; Expression = {$_.Message.SubString($_.Message.LastIndexOf("Network Account Name:") -195,300)}},Id, TimeCreated, Message -First 10 | fl Id, TimeCreated, Info


Further to this, to find all the times a particular user has logged on to a machine, use the following query


Get-WinEvent -LogName 'Security' -FilterXPath 'Event[System[EventID=4624] and EventData[Data[@Name="TargetUserName"]="justusernamenodomain"]]' -MaxEvents 10 | fl id, timecreated


Alternatively you can edit the custom filter in the event log to look like this


<QueryList>

  <Query Id="0" Path="Security">

    <Select Path="Security">*[System[(EventID=4624) and TimeCreated[@SystemTime&gt;='2022-04-25T15:30:20.000Z' and @SystemTime&lt;='2022-04-25T16:30:20.999Z']]]

and *[EventData[Data[@Name="LogonType"]=10]]

</Select>

  </Query>

</QueryList>




Tuesday, 22 January 2019

How to retrieve a list of programs installed on Windows using PowerShell

Use the following powershell command

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Sort-object -Property DisplayName | Format-Table –AutoSize | Out-File \temp\myinstalls.txt

Friday, 4 November 2016

Powershell for finding hotfixes

One liner:

$Session = New-Object -ComObject Microsoft.Update.Session; $Searcher = $Session.CreateUpdateSearcher(); $HistoryCount = $Searcher.GetTotalHistoryCount();$Searcher.QueryHistory(0,$HistoryCount) | Sort-Object -Property Date -Descending | Select Title, Date | Export-Csv -Path c:\temp\hotfixlist.csv

More full version:


$wu = new-object -com “Microsoft.Update.Searcher”

$totalupdates = $wu.GetTotalHistoryCount()

$all = $wu.QueryHistory(0,$totalupdates)

# Define a new array to gather output
$OutputCollection=  @()
             
Foreach ($update in $all)
    {
    $string = $update.title

    $Regex = “KB\d*”
    $KB = $string | Select-String -Pattern $regex | Select-Object { $_.Matches }

     $output = New-Object -TypeName PSobject
     $output | add-member NoteProperty “HotFixID” -value $KB.‘ $_.Matches ‘.Value
     $output | add-member NoteProperty “Title” -value $string
     $OutputCollection += $output

    }

# Oupput the collection sorted and formatted:
$OutputCollection | Sort-Object HotFixID | Format-Table -AutoSize | Out-File c:\temp\output.txt

Further reading
https://github.com/tomarbuthnot/Get-MicrosoftUpdate

Friday, 2 September 2016

How to retrieve the logged on user of a remote machine in powershell

Note: For windows 7 desktop users you’ll need to install the active directory modules for powershell by following the installation steps here
https://www.microsoft.com/en-gb/download/details.aspx?id=7887

A better version could be to filter the process for explorer.exe

Get-WmiObject -class win32_process -Filter "name = 'Explorer.exe'" -ComputerName MACHINENAME -EA "Stop" | % {$_.GetOwner().User}

Or if you wish to resolve down to the actual full person's name

Get-WmiObject -class win32_process -Filter "name = 'Explorer.exe'" -ComputerName WDUKLON-0102 -EA "Stop" | % {Get-AdUser -Identity $_.GetOwner().User | Select -Property Name}

For all logged on users though, use the following script…

 https://gallery.technet.microsoft.com/scriptcenter/d46b1f3b-36a4-4a56-951b-e37815a2df0c
function Get-LoggedOnUser {
#Requires -Version 2.0           
[CmdletBinding()]           
Param            
   (                      
    [Parameter(Mandatory=$true,
               Position=0,                         
               ValueFromPipeline=$true,           
               ValueFromPipelineByPropertyName=$true)]           
    [String[]]$ComputerName
   )#End Param

Begin           
{           
Write-Host "`n Checking Users . . . "
$i = 0           
}#Begin         
Process           
{
    $ComputerName | Foreach-object {
    $Computer = $_
    try
        {
            $processinfo = @(Get-WmiObject -class win32_process -ComputerName $Computer -EA "Stop")
                if ($processinfo)
                {   
                    $processinfo | Foreach-Object {$_.GetOwner().User} |
                    Where-Object {$_ -ne "NETWORK SERVICE" -and $_ -ne "LOCAL SERVICE" -and $_ -ne "SYSTEM"} |
                    Sort-Object -Unique |
                    ForEach-Object { New-Object psobject -Property @{Computer=$Computer;LoggedOn=$_} } |
                    Select-Object Computer,LoggedOn
                }#If
        }
    catch
        {
            "Cannot find any processes running on $computer" | Out-Host
        }
     }#Forech-object(ComputerName)      
           
}#Process
End
{

}#End
}#Get-LoggedOnUser

Friday, 19 August 2016

ASCII art with Powershell

$colors = [System.ConsoleColor]::GetValues([System.ConsoleColor]); 1..100 | % { $var= ($_ %= $colors.Length ); Write-Host $var.ToString().PadRight($var * 10, '*') -ForegroundColor $colors[$var] -BackgroundColor $colors[$var -1 ] }

image

Tuesday, 2 August 2016

Extract file version from all machines on network using powershell

cls
$computers = (Get-ADComputer -Filter "Name -like 'WDUKLON*'" | select -ExpandProperty Name)

$ErrorActionPreference = 'SilentlyContinue'

$computers | % {
    $computername = $_;
    $dllfile = (get-childitem "\\$computername\c$\Program Files (x86)\RRA\Beacon\RRA.Beacon.Recruiter.Business.dll" -ErrorAction SilentlyContinue);
    $fileversion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($dllfile).FileVersion;
    If (!$fileversion.ToString().StartsWith("4") ) {"{0}`t{1}" -f $computername, $fileversion.ToString()}
    }

N.B. RSA pack will need installing on win 7 machine https://www.microsoft.com/en-gb/download/details.aspx?id=7887

Wednesday, 13 January 2016

Extract job titles from AD using powershell

For a given list of userids in a file called users.txt use the following powershell command in the same directory


Get-Content users.txt | foreach {Get-ADUser -Identity $PSItem -Properties mail,title | select -Property mail, title} |Export-Csv users.csv

Or use this to find new starters in the organisation...

$lastWeek = (get-date).AddDays(-31);

Get-ADUser -Filter "Description -like 'London'"  -Properties Name, Title, Manager, whenCreated, DistinguishedName, LastLogonDate | ? whenCreated  -gt $lastWeek | select Name, Title, Manager, whenCreated, DistinguishedName, LastLogonDate | fl

Note: For windows 7 desktop users you’ll need to install the active directory modules for powershell by following the installation steps here
https://www.microsoft.com/en-gb/download/details.aspx?id=7887
For all active directory attributes / propery names, see this link here
http://www.kouti.com/tables/userattributes.htm
Another way to have done it would have been usng SQL via a linked server
https://www.mssqltips.com/sqlservertip/2580/querying-active-directory-data-from-sql-server/
e.g.
SELECT     *
FROM OPENQUERY( ADSI,
    'SELECT samaccountname, mail, title, sn
     FROM ''LDAP://dc=companyname,dc=com''
     WHERE objectCategory = ''Person'' AND objectClass= ''user''
     AND userprincipalname = ''*'' AND mail = ''*'' AND SN = ''*''
         ORDER BY useraccountcontrol
      ')
      Where
      samaccountname= ‘myaccountloginname’

Wednesday, 16 December 2015

Speech with windows powershell

Set-ExecutionPolicy Unrestricted -Force

<#
.Synopsis
   Allows you to speak on a remote computer
   Requires that you have run winrm qc on the remote machine
   or Enable-PSRemoting. And on the local machine you've changed
   Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value * -Force 
.DESCRIPTION
   Allows you to speak on a remote computer
.EXAMPLE
   Speak-Remote 1 "How are you today" REMOTE_PC
.EXAMPLE
   Speak-Remote -RemoteComputerName REMOTE_PC
#>
function Speak-Remote
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]
        $Times = (Read-Host "How many Times"),

        # Param2 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]
        $Message = (Read-Host "What should I say"),

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
        [string]
        $RemoteComputerName
    )

    Begin
    {
    }
    Process
    {
        Invoke-Command -ScriptBlock {Param($msg, $n) Add-Type -AssemblyName System.Speech; $o = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer; $o.SelectVoice("Microsoft Zira Desktop") ; $y = 0; do { $o.Speak($msg);$y = $y + 1;} until ($y -eq $n) } -ComputerName $RemoteComputerName -ArgumentList $Message, $Times
    }
    End
    {
    }
}

Speak-Remote -RemoteComputerName REMOTE_PC

Wednesday, 21 May 2014

Remove capitalization from Visual Studio 2012 / 2013 menus

http://blogs.msdn.com/b/zainnab/archive/2012/06/14/turn-off-the-uppercase-menu-in-visual-studio-2012.aspx

Manual Registry Change

Open the registry editor and go to HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\General\
(For Windows 8 Desktop Express go to HKCU\Software\Microsoft\WDExpress\11.0\General) //special thanks to msm8bball for the update
(For Web Express go to HKEY_CURRENT_USER\Software\Microsoft\VSWDExpress\11.0\General)

  1. Create a new DWORD value called SuppressUppercaseConversion set to 1

or

PowerShell Goodness

In the PowerShell window copy the script below and paste it in then press Enter:
Set-ItemProperty -Path HKCU:\Software\Microsoft\VisualStudio\11.0\General -Name SuppressUppercaseConversion -Type DWord -Value 1

How to find the last interactive logons in Windows using PowerShell

Use the following powershell script to find the last users to login to a box since a given date, in this case the 21st April 2022 at 12pm un...