{"id":56,"date":"2018-01-21T06:02:01","date_gmt":"2018-01-21T06:02:01","guid":{"rendered":"http:\/\/107.181.191.134\/?page_id=18"},"modified":"2021-02-15T03:45:27","modified_gmt":"2021-02-15T03:45:27","slug":"powershell","status":"publish","type":"page","link":"https:\/\/certcent.io\/index.php\/powershell\/","title":{"rendered":"PowerShell"},"content":{"rendered":"<p><span style=\"color: #ffff00;\">Snippets that are useful for small business administrating Windows:<\/span><\/p>\n<pre class=\"lang:default decode:true \" title=\"Quick and dirty parse of 2012R2 Security domain log \"><span style=\"color: #ffff00;\">Find user that matches like expression with successful logins on a Windows 7 computer.\nGet-WinEvent -FilterHashtable @{ id='4624' ; logname='security' } | where-object {$_.Properties[5].value -like \"*jeffrey*\" } | select TimeCreated, @{Label=\"User\"; Expression={ $_.Properties[5].value} } , @{Label=\"Computer\"; Expression={ $_.Properties[18].value} }<\/span><\/pre>\n<pre class=\"lang:default decode:true \" title=\"ADSI Forensics \"><span style=\"color: #ffff00;\">&lt;#\n.DESCRIPTION\nFIND USERS LAST LOGIN\n#&gt;\nfunction last-logon { param($username) get-aduser $username -properties * | select-object name, @{name=\u201dlastlogon\u201d;expression={[datetime]::fromfiletime($_.lastlogon)}} | s\nort-object lastlogon\n&lt;#\n.DESCRIPTION\nGet logon failures or success\n#&gt;\nfunction GetLogonFailures {\n     Get-WinEvent -FilterHashTable @{ logname='security'; id=4625 } |\n     select-object TimeCreated,\n     @{Label=\"Username\"; Expression={ $_.Properties[5].Value } } ,\n     @{ Label = \"Domain\" ; Expression={ $_.Properties[6].Value } }  ,\n     @{ Label = \"Source IP Address\"; Expression={ $_.Properties[19].Value } }\n        }\nfunction GetLogonSuccesses {\n     Get-WinEvent -FilterHashTable @{ logname='security'; id=4624 } |\n     select-object TimeCreated,\n     @{Label=\"Username\"; Expression={ $_.Properties[5].Value } },\n     @{ Label = \"Domain\" ; Expression={ $_.Properties[6].Value } } ,\n     @{ Label = \"Source IP Address\"; Expression={ $_.Properties[18].Value } }\n        }\nAnother quick and dirty ADSI users and logon time sorted.\nget-aduser -properties * -filter *| select Name, @{name = \"lastlogon\";expression={[datetime]::fromfiletime($_.lastlogon)}} |sort-object lastlogon\n&lt;#\n.DESCRIPTION\nGet group membership\n#&gt;\nfunction group-membership {\nparam($name)\n$adsi = new-object system.directoryservices.directorysearcher\n$adsi.filter = \"(&amp;(objectCategory=user)(samAccountname=$name)) \"\n$groups = $adsi.findone().properties.memberof\nforeach ($strGroup in $groups) {\n$strGroup = $strGroup.split(',')[0]\n$strGroup = $strGroup.split('=')[1]\n$strGroup\n\t}\n}\n&lt;#\n.DESCRIPTION\nObtain metadata for username\n#&gt;\nfunction get-adminmetadata { param($username) get-aduser $username | get-adreplicationattributemetadata -server localhost | ft LastOriginatingChangeTime,LocalChangeUsn, LastOriginatingChangeDirectoryServerIdentity, LastOriginatingChangeUsn,AttributeName,Version}\n&lt;#\n.DESCRIPTION\nFind history of users added to groups.\n#&gt;\nfunction get-usergrouphistory { param($username) $userobj = get-aduser $username ; get-aduser itadmin -Properties memberof |  select-object -ExpandProperty memberof | foreach-object { Get-ADReplicationAttributeMetadata $_ -ShowAllLinkedValues -server localhost | where-object {$_.AttributeName -eq \"member\" -and $_.AttributeValue -eq  $userobj }  | select-object FirstOriginatingCreateTime,Object,AttributeValue  | sort-object FirstOriginatingCreateTime -Descending }  | ft  }\n&lt;#\n.DESCRIPTION\nSample of xml query from security logs\n#&gt;\nfunction queryEventlog {\n[XML]$query = @\"\n&lt;QueryList&gt;\n  &lt;Query Id=\"0\" Path=\"Security\"&gt;\n    &lt;Select Path=\"Security\"&gt;*[System[(EventID=4624)]]&lt;\/Select&gt;\n  &lt;\/Query&gt;\n&lt;\/QueryList&gt;\n\"@\nGet-WinEvent -filterxml $query\n}\n&lt;#\n.DESCRIPTION\nSample using Gridview PassThru on Windows Logs\n#&gt;\nfunction PassThru { { Get-EventLog -list | Out-GridView -PassThru | foreach { $_.Log; Get-EventLog -LogName $_.Log -Newest 10 } }\n<\/span><\/pre>\n<pre class=\"lang:default decode:true\" title=\"AD Cleaning\"><span style=\"color: #ffff00;\">&lt;#\n.DESCRIPTION\nEnable the recycle bin (restore AD object)\nlogontime: [datetime]::findtimestamp\nFind Stale Groups\nMove account to org, disable after 30-days, delete after 90-days\nComputer delete A, AAAA, and PTR records.\n#&gt;\n&lt;#\n.DESCRIPTION\nFind ADGroups, display member counts, and when last changed.\n#&gt;\nfunction stale-groups { get-adgroup -filter * -properties Name , whencreated, whenchanged, member, memberof | select-object name, whencreated, member, whenchanged, memberof, description, @{name ='membercount'; expression={$_.member.count}}}\n&lt;#\n.DESCRIPTION\nFind Stale Users\n#&gt;\nfunction findlastlogon { param($username) get-aduser $username -properties * | select-object name, @{name=\u201dlastlogon\u201d;expression={[datetime]::fromfiletime($_.lastlogon)}} | sort-object lastlogon }\n&lt;#\n.DESCRIPTION\nFind all computers based on XP\n#&gt;\n function oldxpcomputers {get-adcomputer -filter {OperatingSystem -like \"*XP*\"}  -properties WhenChanged,lastlogontimestamp | select-object name, whenchanged, @{name='lasttime';expression={[datetime]::FromFileTimeUTC($_.LastLogonTimeSTamp)}}}\n<\/span><\/pre>\n<p><span style=\"color: #ffff00;\">\u00a0<\/span><br \/>\n<span style=\"color: #ffff00;\">Enabled AD Recycle Bin (Forest and Domain 2012+) in Powershell:<\/span><\/p>\n<pre class=\"lang:default decode:true \" title=\"Enable AD Recycle Bin\"><span style=\"color: #ffff00;\"># Pull the full name and path to recycle bin (can be very long)\n$name = Get-ADOptionalFeature -filter *\nEnable-ADOptionalFeature -Identity \"$name.DistinguishedName\"\n-Target domain.com -Scope ForestOrConfigurationSet<\/span><\/pre>\n<p><span style=\"color: #ffff00;\">Find files older then days:<\/span><\/p>\n<pre class=\"lang:default decode:true \" title=\"Find old files and run command against. \"><span style=\"color: #ffff00;\"># This scripts will identify old files in backup directories and remove them\n#\n$date = get-date\n$directories = \"Production\",\"JBSettings\",\"UniPoint_Live\",\"UniPoint_unidx\"\nforeach ($oldfiles in $directories)\n{ gci $oldfiles | where-object {$_.LastWriteTime.AddDays(3) -lt $date }  }<\/span><\/pre>\n<p><span style=\"color: #ffff00;\">Find 10 largest files in directory e:\\Library:<\/span><\/p>\n<pre class=\"left-set:true lang:default decode:true\" title=\"Top Largest Files\"><span style=\"color: #ffff00;\">invoke-command -ComputerName 192.168.1.1 -Credential $cred -ScriptBlock { gci e:\\library -Recurse | Sort-Object -Descending Length | select -First 10 }\n<\/span><\/pre>\n<p><span style=\"color: #ffff00;\">Here&#8217;s a simple, but very powerful and useful script to parse your Windows logs. Beginning in Windows 2008 Get-WinEvent replaced Get-EventLog.<\/span><\/p>\n<pre class=\"left-set:true lang:default decode:true\" title=\"Search Windows' Security Logs\"><span style=\"color: #ffff00;\">function GetLogonFailures {\n     Get-WinEvent -FilterHashTable @{ logname='security'; id=4625 } |\n     select-object TimeCreated,\n     @{Label=\"Username\"; Expression={ $_.Properties[5].Value } } ,\n     @{ Label = \"Domain\" ; Expression={ $_.Properties[6].Value } }  ,\n     @{ Label = \"Source IP Address\"; Expression={ $_.Properties[19].Value } }\n        }\nfunction GetLogonSuccesses {\n     Get-WinEvent -FilterHashTable @{ logname='security'; id=4624 } |\n     select-object TimeCreated,\n     @{Label=\"Username\"; Expression={ $_.Properties[5].Value } },\n     @{ Label = \"Domain\" ; Expression={ $_.Properties[6].Value } } ,\n     @{ Label = \"Source IP Address\"; Expression={ $_.Properties[18].Value } }\n        }\n<\/span><\/pre>\n<p><span style=\"color: #ffff00;\">This function can be used to extract a Active Directory user&#8217;s group memberships and copy them to an array.<\/span><\/p>\n<pre class=\"lang:default decode:true\" title=\"List group memberships for user.\"><span style=\"color: #ffff00;\">function group-membership {\nparam($name)\n$adsi = new-object system.directoryservices.directorysearcher\n$adsi.filter = \"(&amp;(objectCategory=user)(samAccountname=$name)) \"\n$groups = $adsi.findone().properties.memberof\nforeach ($strGroup in $groups) {\n$strGroup = $strGroup.split(',')[0]\n$strGroup = $strGroup.split('=')[1]\n$strGroup\n\t}\n}<\/span><\/pre>\n<p><span style=\"color: #ffff00;\">A fun function to avoid spammers with encoding your e-mail address.<\/span><\/p>\n<pre class=\"lang:default decode:true \" title=\"Encode and Decode functions in Powershell\"><span style=\"color: #ffff00;\">function EncodeEmail { param($string)\n$encode = $string;\n$bytes=[System.Text.Encoding]::Unicode.GetBytes($encode);\n$EncodedText=[Convert]::ToBase64String($bytes);\n$EncodedText }\nfunction DecodeEMail { param($string)\n$decode = $string;\n$decoded = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($decode))\n$decoded;\n}<\/span><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Snippets that are useful for small business administrating Windows: Find user that matches like expression with successful logins on a Windows 7 computer. Get-WinEvent -FilterHashtable @{ id=&#8217;4624&#8242; ; logname=&#8217;security&#8217; } | where-object {$_.Properties[5].value -like &#8220;*jeffrey*&#8221; } | select TimeCreated, @{Label=&#8221;User&#8221;; Expression={ $_.Properties[5].value} } , @{Label=&#8221;Computer&#8221;; Expression={ $_.Properties[18].value} } &lt;# .DESCRIPTION FIND USERS LAST LOGIN #&gt;&hellip; <a class=\"more-link\" href=\"https:\/\/certcent.io\/index.php\/powershell\/\">Continue reading <span class=\"screen-reader-text\">PowerShell<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":[],"_links":{"self":[{"href":"https:\/\/certcent.io\/index.php\/wp-json\/wp\/v2\/pages\/56"}],"collection":[{"href":"https:\/\/certcent.io\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/certcent.io\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/certcent.io\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/certcent.io\/index.php\/wp-json\/wp\/v2\/comments?post=56"}],"version-history":[{"count":1,"href":"https:\/\/certcent.io\/index.php\/wp-json\/wp\/v2\/pages\/56\/revisions"}],"predecessor-version":[{"id":384,"href":"https:\/\/certcent.io\/index.php\/wp-json\/wp\/v2\/pages\/56\/revisions\/384"}],"wp:attachment":[{"href":"https:\/\/certcent.io\/index.php\/wp-json\/wp\/v2\/media?parent=56"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}