Windows PowerShell
1161 TopicsTable of Basic PowerShell Commands
The chart lists Windows PowerShell command aliases, the Windows PowerShell cmdlet name, and a description of what the command actually does. Command alias Cmdlet name Description of command % ForEach-Object Performs an operation against each item in a collection of input objects. ? Where-Object Selects objects from a collection based on their property values. ac Add-Content Appends content, such as words or data, to a file. asnp Add-PSSnapIn Adds one or more Windows PowerShell snap-ins to the current session. cat Get-Content Gets the contents of a file. cd Set-Location Sets the current working location to a specified location. chdir Set-Location Sets the current working location to a specified location. clc Clear-Content Deletes the contents of an item, but does not delete the item. clear Clear-Host Clears the display in the host program. clhy Clear-History Deletes entries from the command history. cli Clear-Item Deletes the contents of an item, but does not delete the item. clp Clear-ItemProperty Deletes the value of a property but does not delete the property. cls Clear-Host Clears the display in the host program. clv Clear-Variable Deletes the value of a variable. cnsn Connect-PSSession Reconnects to disconnected sessions compare Compare-Object Compares two sets of objects. copy Copy-Item Copies an item from one location to another. cp Copy-Item Copies an item from one location to another. cpi Copy-Item Copies an item from one location to another. cpp Copy-ItemProperty Copies a property and value from a specified location to another location. curl Invoke-WebRequest Gets content from a webpage on the Internet. cvpa Convert-Path Converts a path from a Windows PowerShell path to a Windows PowerShell provider path. dbp Disable-PSBreakpoint Disables the breakpoints in the current console. del Remove-Item Deletes files and folders. diff Compare-Object Compares two sets of objects. dir Get-ChildItem Gets the files and folders in a file system drive. dnsn Disconnect-PSSession Disconnects from a session. ebp Enable-PSBreakpoint Enables the breakpoints in the current console. echo Write-Output Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console. epal Export-Alias Exports information about currently defined aliases to a file. epcsv Export-Csv Converts objects into a series of comma-separated (CSV) strings and saves the strings in a CSV file. epsn Export-PSSession Imports commands from another session and saves them in a Windows PowerShell module. erase Remove-Item Deletes files and folders. etsn Enter-PSSession Starts an interactive session with a remote computer. exsn Exit-PSSession Ends an interactive session with a remote computer. fc Format-Custom Uses a customized view to format the output. fl Format-List Formats the output as a list of properties in which each property appears on a new line. foreach ForEach-Object Performs an operation against each item in a collection of input objects. ft Format-Table Formats the output as a table. fw Format-Wide Formats objects as a wide table that displays only one property of each object. gal Get-Alias Gets the aliases for the current session. gbp Get-PSBreakpoint Gets the breakpoints that are set in the current session. gc Get-Content Gets the contents of a file. gci Get-ChildItem Gets the files and folders in a file system drive. gcm Get-Command Gets all commands. gcs Get-PSCallStack Displays the current call stack. gdr Get-PSDrive Gets drives in the current session. ghy Get-History Gets a list of the commands entered during the current session. gi Get-Item Gets files and folders. gjb Get-Job Gets Windows PowerShell background jobs that are running in the current session. gl Get-Location Gets information about the current working location or a location stack. gm Get-Member Gets the properties and methods of objects. gmo Get-Module Gets the modules that have been imported or that can be imported into the current session. gp Get-ItemProperty Gets the properties of a specified item. gps Get-Process Gets the processes that are running on the local computer or a remote computer. group Group-Object Groups objects that contain the same value for specified properties. gsn Get-PSSession Gets the Windows PowerShell sessions on local and remote computers. gsnp Get-PSSnapIn Gets the Windows PowerShell snap-ins on the computer. gsv Get-Service Gets the services on a local or remote computer. gu Get-Unique Returns unique items from a sorted list. gv Get-Variable Gets the variables in the current console. gwmi Get-WmiObject Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes. h Get-History Gets a list of the commands entered during the current session. history Get-History Gets a list of the commands entered during the current session. icm Invoke-Command Runs commands on local and remote computers. iex Invoke-Expression Runs commands or expressions on the local computer. ihy Invoke-History Runs commands from the session history. ii Invoke-Item Performs the default action on the specified item. ipal Import-Alias Imports an alias list from a file. ipcsv Import-Csv Creates table-like custom objects from the items in a CSV file. ipmo Import-Module Adds modules to the current session. ipsn Import-PSSession Imports commands from another session into the current session. irm Invoke-RestMethod Sends an HTTP or HTTPS request to a RESTful web service. ise powershell_ise.exe Explains how to use the PowerShell_ISE.exe command-line tool. iwmi Invoke-WMIMethod Calls Windows Management Instrumentation (WMI) methods. iwr Invoke-WebRequest Gets content from a web page on the Internet. kill Stop-Process Stops one or more running processes. lp Out-Printer Sends output to a printer. ls Get-ChildItem Gets the files and folders in a file system drive. man help Displays information about Windows PowerShell commands and concepts. md mkdir Creates a new item. measure Measure-Object Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text. mi Move-Item Moves an item from one location to another. mount New-PSDrive Creates temporary and persistent mapped network drives. move Move-Item Moves an item from one location to another. mp Move-ItemProperty Moves a property from one location to another. mv Move-Item Moves an item from one location to another. nal New-Alias Creates a new alias. ndr New-PSDrive Creates temporary and persistent mapped network drives. ni New-Item Creates a new item. nmo New-Module Creates a new dynamic module that exists only in memory. npssc New-PSSessionConfigurationFile Creates a file that defines a session configuration. nsn New-PSSession Creates a persistent connection to a local or remote computer. nv New-Variable Creates a new variable. ogv Out-GridView Sends output to an interactive table in a separate window. oh Out-Host Sends output to the command line. popd Pop-Location Changes the current location to the location most recently pushed to the stack. You can pop the location from the default stack or from a stack that you create by using the Push-Location cmdlet. ps Get-Process Gets the processes that are running on the local computer or a remote computer. pushd Push-Location Adds the current location to the top of a location stack. pwd Get-Location Gets information about the current working location or a location stack. r Invoke-History Runs commands from the session history. rbp Remove-PSBreakpoint Deletes breakpoints from the current console. rcjb Receive-Job Gets the results of the Windows PowerShell background jobs in the current session. rcsn Receive-PSSession Gets results of commands in disconnected sessions. rd Remove-Item Deletes files and folders. rdr Remove-PSDrive Deletes temporary Windows PowerShell drives and disconnects mapped network drives. ren Rename-Item Renames an item in a Windows PowerShell provider namespace. ri Remove-Item Deletes files and folders. rjb Remove-Job Deletes a Windows PowerShell background job. rm Remove-Item Deletes files and folders. rmdir Remove-Item Deletes files and folders. rmo Remove-Module Removes modules from the current session. rni Rename-Item Renames an item in a Windows PowerShell provider namespace. rnp Rename-ItemProperty Renames a property of an item. rp Remove-ItemProperty Deletes the property and its value from an item. rsn Remove-PSSession Closes one or more Windows PowerShell sessions (PSSessions). rsnp Remove-PSSnapin Removes Windows PowerShell snap-ins from the current session. rujb Resume-Job Restarts a suspended job rv Remove-Variable Deletes a variable and its value. rvpa Resolve-Path Resolves the wildcard characters in a path, and displays the path contents. rwmi Remove-WMIObject Deletes an instance of an existing Windows Management Instrumentation (WMI) class. sajb Start-Job Starts a Windows PowerShell background job. sal Set-Alias Creates or changes an alias (alternate name) for a cmdlet or other command element in the current Windows PowerShell session. saps Start-Process Starts one or more processes on the local computer. sasv Start-Service Starts one or more stopped services. sbp Set-PSBreakpoint Sets a breakpoint on a line, command, or variable. sc Set-Content Replaces the contents of a file with contents that you specify. select Select-Object Selects objects or object properties. set Set-Variable Sets the value of a variable. Creates the variable if one with the requested name does not exist. shcm Show-Command Creates Windows PowerShell commands in a graphical command window. si Set-Item Changes the value of an item to the valu See the original here.8.3KViews13likes0CommentsCant no longer change OWA's signature
Hello all, I am trying to update my Outlook Web's signature with Powershell, like I always do, with the "Set-MailboxMessageConfiguration" command, but the signature is not updated. But "Get-MailboxMessageConfiguration" shows that the new signature is there OWA allows now for some people/organitations to manage multiple signatures, but I can't find any documentation/information about that. So, how I can modify the already existing signature? Or, how I can create a new signature?10KViews6likes16CommentsThreat Hunting with PowerShell - Security even with a small budget - there is no excuse!
Dear Threat Hunter, Lack of IT security is often excused by little or no available money. In my view, this is a very poor excuse. In this article I will try to give you a jump start on how to investigate threats with PowerShell. Is this a comprehensive and conclusive list of how you can find or detect threats/threats? NO, absolutely not. But it is meant to provide you with the support that you need to move forward on your own. Let's talk about the "general conditions": 1. If you use the PowerShell scripts I show/explain in this article, this is entirely your responsibility. I use the scripts in different situations, they are not dangerous, but you should already know what you are doing. 2. Written permission! If you are not sure if you are allowed to do an investigation, organize a written permission from your supervisor. 3. In the different scripts I sometimes (for this article deliberately) use standard search words like "malware", "malicious", "hacker" etc. Such search patterns/search words need to be customized, of course. These simply serve as an example. 4. The last part of the article examines some Microsoft cloud services. I am absolutely aware that there are a huge number of tools for hunting in the Microsoft cloud services. It starts with Azure Sentinel and continues with Cloud App Security. Since the focus is on a small budget, I'll leave those tools on the side. Introduction: So first, why should you use PowerShell for threat hunting? PowerShell is a useful threat hunting tool because it is a powerful scripting language and a platform for automating tools and accessing data across any Windows environment. It allows you to quickly gather information from various sources such as event logs, registries, files, and processes. Additionally, it can also be easily integrated with other tools and technologies making it a flexible and efficient tool for threat hunting. Some common use cases for PowerShell in the threat hunting environment include automated collection of log data, identification of unusual behavior anomalies in the system, the discovery of malware or malicious activity by known signatures or patterns or behaviors. These are just a few examples of how PowerShell can be used in a threat hunting capacity. Its versatility and ability to access and manipulate data from across the Windows environment make it a very valuable tool for any security professional. Threat Hunting in PowerShell - Use Cases: All right. So now that we understand where PowerShell can benefit an organization from a threat hunting perspective. Let's take a deeper look at some of the actual use cases you might encounter on a day to day basis, first being identify malicious processor files. So specifically, you can conduct raw file analysis to sift through different data shares to look for particular files in question whether that be a signature or even an extension of a certain file being able to quickly search and triage through files is an extreme benefit of using PowerShell for threat hunting. But how exactly do we start, what can we use as a guide? For example, the MITRE ATT&CK Framework. Here are a few examples: Indicator Removal: Clear Windows Event Logs https://attack.mitre.org/techniques/T1070/001/ Event Triggered Execution: Installer Packages https://attack.mitre.org/techniques/T1546/016/ Hide Artifacts: NTFS File Attributes https://attack.mitre.org/techniques/T1564/004/ Command and Scripting Interpreter: PowerShell https://attack.mitre.org/techniques/T1059/001/ Command and Scripting Interpreter: Windows Command Shell https://attack.mitre.org/techniques/T1059/003/ Event Triggered Execution: Windows Management Instrumentation Event Subscription https://attack.mitre.org/techniques/T1546/003/ Credentials from Password Stores: Windows Credential Manager https://attack.mitre.org/techniques/T1555/004/ Abuse Elevation Control Mechanism: Bypass User Account Control https://attack.mitre.org/techniques/T1548/002/ The MITRE ATT@CK framework provides a comprehensive and regularly updated overview of tactics, techniques, and procedures (TTPs) used by various threat actors. We can locate these TTPs using PowerShell, here are a few examples: Indicator Removal: Clear Windows Event Logs https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/06_Account_Events.ps1 Event Triggered Execution: Installer Packages https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/08_Get-ItemProperty_Software.ps1 Hide Artifacts: NTFS File Attributes https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/08_Get-ItemProperty_Software.ps1 Windows Installer Service is running https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/01_WIS_is_running.ps1 Search Alternate Data Streams on NTFS File Systems https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/02_Search_ADS_on_NTFS%20_(specific%20file).ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/03_Search_ADS_on_NTFS_file_systems.ps1 Read the Contents of a File https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/06_Read_the_contents_file.ps1 Locating Data Patterns within a File https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/05_locating_data_patterns_within_file.ps1 Search for Encoding with Regex https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/07_Search_encoding_with_regex.ps1 Search for Command and Scripting Interpreter: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/04_Searching_for_PIDs.ps1 Threat hunting in different environments with PowerShell: Coming examples are about collecting information in very different environments. Also here a few examples as a kind => as first starting points: Hunt for Threats in Active Directory: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/01_Resetting_Password_Unlocking_Accounts.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/02_Search_stale_accounts.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/03_Users_without_Manager.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/04_Password_Expiration.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/05_Group_Membership_Report.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/06_Account_Events.ps1 https://github.com/tomwechsler/Active_Directory_Advanced_Threat_Hunting/blob/main/PowerShell/Tracking_the_Source_of_Account_Lock_Outs_and_Bad_Passwords.ps1 https://github.com/tomwechsler/Active_Directory_Advanced_Threat_Hunting/blob/main/PowerShell/Finding_Unused_Group_Policy_Objects.ps1 Some of the scripts are structured in such a way that they must be executed block by block/line by line. So do not execute the whole script at once. Pay attention to the different information that is collected. With some investigations in the Active Directory accounts can be indicated like "guest" or "krbtgt", there must be clear of course how this information is to be estimated. Depending on how and what information is searched. Hunt for Threats in Exchange Online: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Exchange_Online/Exchange_Mailbox_LastLogin.ps1 Find mailboxes with the last login. Hunt for Threats in Azure: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Azure/Collect_vms_subscription.ps1 We search Azure for all virtual machines in a subscription. https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Azure/02_Graph_Create_Time_Last_Password.ps1 When was the last password change and when were the accounts created? Hunt for Threats in SharePoint: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_SharePoint_Online/SharePoint_Online_specific_files.ps1 With this script we search for files with the extension .ps1 in a SharePoint Online page. Summary: Is this the best tactic to hunt for threats? No! There are many different tactics/techniques to search for threats. First of all, there are a huge number of different tools that can be used, for example SIEM/SOAR (Security Information and Event Management/Security Orchestration, Automation and Response). These tools are really great, sometimes cost a lot and often it takes a lot of knowledge to use such tools. But what is the use of such tools if the information generated by these tools cannot be understood properly, not very much. For this reason, I have tried in this article with simple tools to generate information that hopefully can be interpreted. Is finished here at this point. NO, the journey continues. The examples in this article are neither exhaustive nor complete, but they should give you a starting point. I hope you can build on this foundation. I hope that this information is helpful to you and that you have received a good "little" foundation. But I still hope that this information is helpful for you. Thank you for taking the time to read the article. Happy Hunting, Tom Wechsler P.S. All scripts (#PowerShell, Azure CLI, #Terraform, #ARM) that I use can be found on github! https://github.com/tomwechsler62KViews5likes0CommentsPowerShell Predictive IntelliSense - the best thing since sliced bread ⚡
2020 must have been a busy year because I missed one of the greatest new PowerShell features called Predictive IntelliSense. Back in November 2020, Jason Helmick announced PowerShell PSReadLine 2.1 with Predictive IntelliSense. Read my full post here: PowerShell Predictive IntelliSense - Thomas Maurer1.3KViews5likes0CommentsPowerShell ile IP Scan islemi (tr-TR)
PowerShell ile bu makalemizde de network adminleri için basit bir komut ile belirlediğiniz aralıkda IPleri tarayıp hangi IPlerin aktif kullanıldığını belirleyebilirsiniz. Ping komutunun gelişmiş bir hali olarak düşünebilirsiniz. Komut bütünü temelinde kullanmış olduğu ping komutunun reply from cevabı veren IPleri belirleyerek komut satırında görüntülemenizi sağlar. <IP aralıgi> | %{ping -n 1 -w 15 Network IP.$_ | select-string "reply from"} Basit bir örnek ile açıklamak gerekirse IP aralığı için 1 den 254 de kadar bir aralık belirleyip bu aralık arasında IP taraması yapmasını isteyebilirsiniz. Network IP adresi için de Network adresiniz için 192.168.1.$ şeklinde tanımlama yapmanız yeterli olacaktır. 1..254 | %{ping -n 1 -w 15 192.168.1.$_ | select-string "reply from"} Örnek uygulama çıktısı aşağıdaki gibidir. PowerShell 6.2.3 Copyright (c) Microsoft Corporation. All rights reserved. https://aka.ms/pscore6-docs Type 'help' to get help. PS C:\Users\oadmin> 1..254 | %{ping -n 1 -w 15 192.168.1.$_ | select-string "reply from"} Reply from 192.168.1.1: bytes=32 time<1ms TTL=64 Reply from 192.168.1.33: bytes=32 time=42ms TTL=64 Reply from 192.168.1.34: bytes=32 time<1ms TTL=128 Reply from 192.168.1.42: bytes=32 time=2ms TTL=64 İşi biraz daha yukarıya taşımak istersek cevap veren IP adrelerini listelemek istersek de aşağıdaki örnek scripti kullanabilirsiniz. İşlemin sonuçlanması ve kullanılan IPlerin listelenmesi zaman alabilir. 1..255 | foreach-object { (new-objectsystem.net.networkinformation.ping).Send("192.168.1.$_") } | where-object {$_.Status -eq "Success"} | select Address Uygulama çıktısı aşağıdaki gibidir. PowerShell 6.2.3 Copyright (c) Microsoft Corporation. All rights reserved. https://aka.ms/pscore6-docs Type 'help' to get help. PS C:\Users\oadmin> 1..255 | foreach-object { (new-object system.net.networkinformation.ping).Send("192.168.1.$_") } | where-object {$_.Status -eq "Success"} | select Address Address ------- 192.168.1.1 192.168.1.33 192.168.1.34 192.168.1.42 192.168.1.621.6KViews5likes0CommentsPowerShell ile UTF-8 şifrenizi MD5 formatına çevirme (tr-TR)
PowerShell ile yapacağımız işlerin sınırı yok özelikle DB adminlerin çok işine yarayacağını düşündüğüm UTF-8 formatındaki metinleri MD5 formatına çevirmek için kullanabileceğiniz aşağıdaki script kolay bir çözüm yolu olacaktır. Özelikle şifreleme için kullanılan bu yöntem UTF-8 formatındaki şifrelerinizi MD5 formatına çevirecektir. $userPassword = "Sifrenizi bu bolume giriniz" $MD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider $UTF8 = New-Object -TypeName System.Text.UTF8Encoding [System.BitConverter]::ToString($MD5.ComputeHash($UTF8.GetBytes($userPassword))).Replace("-","") Şifremizin "Sifrem123ABab" olduğunu varsayalım scriptimiz ile MD5 formatına çevirelim.Siz şifrenizi MD5 formatına çevirmek için ilgili yeri düzenleyip kullanabilirsiniz. Örnek uygulama çıktısı aşağıdaki gibidir. PowerShell 6.2.3 Copyright (c) Microsoft Corporation. All rights reserved. https://aka.ms/pscore6-docs Type 'help' to get help. PS C:\Users\oadmin> $userPassword = "Sifrem123ABab" PS C:\Users\oadmin> $MD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider PS C:\Users\oadmin> $UTF8 = New-Object -TypeName System.Text.UTF8Encoding PS C:\Users\oadmin> [System.BitConverter]::ToString($MD5.ComputeHash($UTF8.GetBytes($userPassword))).Replace("-","") 3950F983329667789E5AD0D09CC9A7B5 PS C:\Users\oadmin> Sifrem123ABab için MD5 format çıktısı 3950F983329667789E5AD0D09CC9A7B5 şeklindedir.1KViews5likes0CommentsPowerShell ile Outlook uzerinden mail gonderme (tr-TR)
Otomasyon süreçlerinde işinize yarayabileceğini düşündüğüm PowerShell ile outlook üzerinden mail gönderme işlemi çok pratik bir çözüm olabilir. SMTP yada web mail prosedürlerine takılmadan kurulu olan outlook hesabı üzerinden mail gönderimi sağlayan script ile rutin işleriniz için oluşturacağınız zamanlanmış görevleri kullanarak mail gönderimi yapmak çok kolay bir hal alacaktır. Örneğin sisteminiz üzerinde çalışan standart bir script çıktısını mail gönderimi ile paylaşmak istiyorsanız bu scripti modifiye edip kullanabilirsiniz. $Outlook = New-Object -ComObject Outlook.Application $Mail = $Outlook.CreateItem(0) $Mail.To = “Gonderim yapmak istediginiz kisinin mail adresini giriniz.” $date = Get-Date -format “dd/MM/yyyy” $Mail.Subject = “Mail Basligini giriniz.” $Mail.Body = "Mail icerigini giriniz" $Mail.Send() $Mail.Body bölümüne rutin çalışan scriptlerinizin çıktısını tanımlayıp ($example | Out-String) komutu ile mailin içine ekleyebilirsiniz.2.4KViews5likes0CommentsPowerShell ile RDP ataklarını engellemenin yolu (tr-TR)
Windows firewall üzerinde oluşturaacağınız RDP atak engelleme kurallınıza atak yapan IP adreslerini ekleyen bu script ile yanlış deneme yapan RDP isteklerinin IP adreslerini windows firewall üzerindeki kuralınıza ekliyor. # Firewall uzerinde tanimladiginiz kuralin adini yazınız $firewallRuleName = "RDP Atak Engelle" # Karalisteye eklenmetecek IP adreslerini yada hostnamelerini tanimlayiniz. $whiteList = @( [System.Net.Dns]::GetHostAddresses("powershell-ozan, Ozan-WI, 192.168.2.101").IPAddressToString ) ### kod ### Write-Host "Running at $(Get-Date)" $regExIp = "\d\d?\d?.\d\d?\d?.\d\d?\d?.\d\d?\d?" # RDS icin olusan Event loglardan 140 tanesini incele $currentAttackers = Get-Winevent Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational | Where-Object {$_.Id -eq 140} | Select Message -ExpandProperty Message # Response yok ise saldırı yoktur. if ($currentAttackers -eq $null) { Write-Host "No current attackers" return } # Her saldırı mesajını alın ve yukarıdaki regExIP'i kullanarak IP'yi filtreleyin for ($i = 0; $i -lt $currentAttackers.Count; $i++) { if ($currentAttackers[$i] -match $regExIp){ $currentAttackers[$i] = $Matches[0] } } # Bilinen saldırganları güvenlik duvarı kurallarından alın $knownAttackers = (Get-NetFirewallRule -DisplayName $firewallRuleName | Get-NetFirewallAddressFilter).RemoteAddress if ($knownAttackers -eq $null){ $knownAttackers = @() } $knownAttackers = $knownAttackers | Sort-Object -Unique # Kaydedilen her login kaydını kontrol et ve daha önce saldırgan olarak bilinip bilinmediğini kontrol et foreach($newAttacker in $currentAttackers) { if ($knownAttackers.Contains($newAttacker)) { #Bilinen bir IP ise işlem yapma continue } elseif ($whiteList -contains $newAttacker) { #Beyaz Listeye alınmış ise işlem yapma Write-Host "$newAttacker is dynamically whitelisted" continue } else{ #yeni bir saldırgan kara listeye ekle $knownAttackers += $newAttacker Write-Host "Added $newAttacker" } } # dublicate'leri kaldırın $knownAttackers = $knownAttackers | Sort-Object -Unique Write-Host "$($knownAttackers.Count) IPs on blacklist" # Tüm bilinen ve tüm yeni tespit edilen saldırganlarla Firwall kurallarını düzenle Set-NetFirewallRule -DisplayName $firewallRuleName "RDP Atak Engelle" -RemoteAddress $knownAttackers Write-Host ""992Views5likes0CommentsPowerShell ile RDP Logon-Logoff kayitlarini görüntüleme
Bir çok sistem mühendisinden istenen genel ve kronik bir durumdur. En son ne zaman logon olmuş ne zaman logoff olmuş bilgisi bazen zorunluluktan bazen anlık ihtiyaç durumundan talep edilir. Event log içinde kaybolmanıza gerek yok. 7001 ve 7002 event idlerini sizin için binlerce log dosyasında inceleyip size çıkartan PowerShell scripti aşağıdaki gibidir. $logs = get-eventlog system -ComputerName powershell-ozan -source Microsoft-Windows-Winlogon -After (Get-Date).AddDays(-7); $res = @(); ForEach ($log in $logs) {if($log.instanceid -eq 7001) {$type = "Logon"} Elseif ($log.instanceid -eq 7002){$type="Logoff"} Else {Continue} $res += New-Object PSObject -Property @{Time = $log.TimeWritten; "Event" = $type; User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}}; $res Uygulama çıktısı aşağıdaki gibidir. PS C:\Users\Administrator> $logs = get-eventlog system -ComputerName powershell-ozan -source Microsoft-Windows-Winlogon -After (Get-Date).AddDays(-7); PS C:\Users\Administrator> $res = @(); ForEach ($log in $logs) {if($log.instanceid -eq 7001) {$type = "Logon"} Elseif ($log.instanceid -eq 7002){$type="Logoff"} Else {Continue} $res += New-Object PSObject -Property @{Time = $log.TimeWritten; "Event" = $type; User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}}; PS C:\Users\Administrator> $res Time User Event ---- ---- ----- 31.05.2019 09:16:58 POWERSHELL-OZAN\Administrator Logon 30.05.2019 18:11:02 POWERSHELL-OZAN\Administrator Logoff860Views5likes0CommentsPowerShell ile log dosyalarini arsivleme (tr-TR)
Windows Server işletim sistemlerinde IIS, exchange gibi log dosyalarını düzenli geriye dönük arsivlemek gereken hem yasal olarak hemde kaynak kullanımı tasarufu kapsamında örnek scripti kullanabilirsiniz. 7 gün sonra geriye dönük dosyları arsivleyen scriptdeki $LastWrite=(get-date).AddDays(-7).ToString("MM/dd/yyyy") 7 değerini değiştirerek geriye dönük tutulacak arsiv gün değerini isteğinize uygun güncelleyebilirsiniz. İlgili scripti task scheduler üzerinde yapılandırarak düzenli bir şekilde kullanabilirsiniz. $LogFolder=“Clog_Dosyasi” $Arcfolder=ClogsArsiv_Log_Dosyasi” $LastWrite=(get-date).AddDays(-7).ToString(MMddyyyy) If ($Logs = get-childitem $LogFolder Where-Object {$_.LastWriteTime -le $LastWrite -and !($_.PSIsContainer)} sort-object LastWriteTime) { foreach ($L in $Logs) { $FullName=$L.FullName $WMIFileName= $FullName.Replace(, ) $WMIQuery = Get-WmiObject -Query “SELECT FROM CIM_DataFile WHERE Name='$WMIFileName'“ If ($WMIQuery.Compress()) {Write-Host $FullName Arsivleme basarili.-ForegroundColor Green} else {Write-Host $FullName Arsivleme hatasi. -ForegroundColor Red}942Views5likes0Comments