Recent Discussions
Welcome to the Windows PowerShell Community!
By popular demand we have created a Windows PowerShell community on the Microsoft Tech Community! Please post questions, best practices and answer questions posted here! Make sure you use labels suggested in each post to help people find your posts. We are looking for suggestions on new spaces to create here so let us know if you have recommendations on what we can do here to make this community a great place for everyone to learn more about Windows PowerShell.5.2KViews15likes13CommentsTable 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.3KViews13likes0CommentsResolveIPtoName ile IP adreslerinin ait olduğu FQDN adresini bulabilirsiniz (tr-TR)
Resolve-DnsName iş sürecini tersten düşünelim. elimizde IP var bu IP aderesine ait FQDN çözümlenmesine ihtiyacımız var. Bunun için çok basit bir script çalıştırdıktan sonra "ReolveIPtoName" komutu ile iş sürecinizi yönetebilirsiniz. PowerShell script function ResolveIPtoName($IP) { $ResolvingResults = "" $ResolvingResults = @() $IPList += @($IP) foreach ($IP in $IPList) { try {$ResolvingResults += [System.Net.Dns]::GetHostEntry($IP)} catch{Write-Host $IP could not be Resolved -BackgroundColor Black -ForegroundColor Red} } $ResolvingResults | Select AddressList, HostName } Uygulama: PS C:\Users\emreozanmemis.MARVEL> function ResolveIPtoName($IP) { >> $ResolvingResults = "" >> $ResolvingResults = @() >> $IPList += @($IP) >> foreach ($IP in $IPList) { >> try {$ResolvingResults += [System.Net.Dns]::GetHostEntry($IP)} >> catch{Write-Host $IP could not be Resolved -BackgroundColor Black -ForegroundColor Red} >> } >> >> $ResolvingResults | Select AddressList, HostName >> } PS C:\Users\emreozanmemis.MARVEL> Çıktı: PS C:\Users\emreozanmemis.MARVEL> ResolveIPtoName 10.172.100.101 AddressList HostName ----------- -------- {fe80::568:93c8:f180:637d%4, 10.172.100.101} shield.marvel.local2.4KViews7likes0CommentsCant 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/tomwechslerPowerShell 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 Exchange 2019 kurulumu ve yapılandırması (tr-TR)
Microsoft'un en değer verdiği servislerinden biri olan Exchange hizmeti her geçen yıl yenilenyor ve güçlenerek servis edilmeye devam ediyor. Cloud ortamının yanı sıra On-Primeses ortamlarında vazgeçilmezi olan Exchange ürün ailesinin son sürümü Exchange 2019 bugün on-primeses ortamda Powershell ile kurulumunu gerçekleştireceğim. Exchange kurması ve yapılandırması biraz zahmetli bir servisdir bu sebeple kurulumu sizler için biraz dah basit bir hale getirerek web sayfalarında gezinip exchnage yüklemesi için gereken özelikleri aramanıza gerek yok. İlk olarka kurulum için gerekli olan Windows Server roles and features yükleyerek başlıyoruz. Exchange için Microsoft Windows Server roles and features yükleyici komutu Install-WindowsFeature NET-Framework-45-Features, RPC-over-HTTP-proxy, RSAT-Clustering, RSAT-Clustering-CmdInterface, RSAT-Clustering-Mgmt, RSAT-Clustering-PowerShell, Web-Mgmt-Console, WAS-Process-Model, Web-Asp-Net45, Web-Basic-Auth, Web-Client-Auth, Web-Digest-Auth, Web-Dir-Browsing, Web-Dyn-Compression, Web-Http-Errors, Web-Http-Logging, Web-Http-Redirect, Web-Http-Tracing, Web-ISAPI-Ext, Web-ISAPI-Filter, Web-Lgcy-Mgmt-Console, Web-Metabase, Web-Mgmt-Console, Web-Mgmt-Service, Web-Net-Ext45, Web-Request-Monitor, Web-Server, Web-Stat-Compression, Web-Static-Content, Web-Windows-Auth, Web-WMI, Windows-Identity-Foundation, RSAT-ADDS Exchange için gerekli olan iki harici uygulamayıda internetten PowerShell ile indirip yüklüyoruz. Windows server için Microsoft .NET Framework 4.8 çevrimdışı yükleyici komutu $WebClient = New-Object System.Net.WebClient $WebClient.DownloadFile("https://go.microsoft.com/fwlink/?linkid=2088631","C:\dotnet.exe") Windows server için Microsoft Visual C++ Redistributable for Visual Studio 2012 Update 4 yükleyici komutu $WebClient = New-Object System.Net.WebClient $WebClient.DownloadFile("https://www.microsoft.com/en-us/download/confirmation.aspx?id=30679&6B49FDFB-8E5B-4B07-BC31-15695C5A2143=1","C:\VSU_4.exe") Yüklemek için C:\ dizinine gelip ilgili uygulamaların yükleme paketlerini çalıştırıyoruz. C:\dotnet.exe C:\VSU_4.exe Exchange kurulumu için Wİndows Server işletim sistemimiz hazırdır. PowerShell de ISO nuzu mount ettiğiniz dizine gidiniz ve aşağıdaki komutları sırası ile çalıştırınız. Setup.exe /IAcceptExchangeServerLicenseTerms /PrepareSchema Setup.exe /IAcceptExchangeServerLicenseTerms /PrepareAD /OrganizationName: <Domain adi> Setup.exe /IAcceptExchangeServerLicenseTerms /PrepareAllDomains Setup.exe /mode:Install /role:Mailbox /IAcceptExchangeServerLicenseTerms ISO dizininde çalıştırabilceğiniz diğer komutlar NOT: Setup.exe [/Mode:] [/IAcceptExchangeServerLicenseTerms] [/Role:] [/InstallWindowsComponents] [/OrganizationName:] [/TargetDir:] [/SourceDir:] [/UpdatesDir:] [/DomainController:] [/DisableAMFiltering] [/AnswerFile:] [/DoNotStartTransport] [/EnableErrorReporting] [/CustomerFeedbackEnabled:] [/AddUmLanguagePack:] [/RemoveUmLanguagePack:] [/NewProvisionedServer:] [/RemoveProvisionedServer:] [/MdbName:] [/DbFilePath:] [/LogFolderPath:] [/ActiveDirectorySplitPermissions:] [/TenantOrganizationConfig:] Kurulum sonrası virtual directory yapılandırması için hostnamenizi yazıp scripti çalıştırınız. $hostname = "" Set-EcpVirtualDirectory "$HostName\ECP (Default Web Site)" -InternalUrl ((Get-EcpVirtualDirectory "$HostName\ECP (Default Web Site)").ExternalUrl) Set-WebServicesVirtualDirectory "$HostName\EWS (Default Web Site)" -InternalUrl ((Get-WebServicesVirtualDirectory "$HostName\EWS (Default Web Site)").ExternalUrl) Set-ActiveSyncVirtualDirectory "$HostName\Microsoft-Server-ActiveSync (Default Web Site)" -InternalUrl ((Get-ActiveSyncVirtualDirectory "$HostName\Microsoft-Server-ActiveSync (Default Web Site)").ExternalUrl) Set-OabVirtualDirectory "$HostName\OAB (Default Web Site)" -InternalUrl ((Get-OabVirtualDirectory "$HostName\OAB (Default Web Site)").ExternalUrl) Set-OwaVirtualDirectory "$HostName\OWA (Default Web Site)" -InternalUrl ((Get-OwaVirtualDirectory "$HostName\OWA (Default Web Site)").ExternalUrl) Set-PowerShellVirtualDirectory "$HostName\PowerShell (Default Web Site)" -InternalUrl ((Get-PowerShellVirtualDirectory "$HostName\PowerShell (Default Web Site)").ExternalUrl) Son olarak send ve recive connectorlerinizi yapılandırınız. Set-ReceiveConnector Set-SendConnector Önemli not domaininiz için DNS A kayıtları MX ve SPF kayıtlarınız için ilgili yönlendirmeleri yaptıktan sonra Exchange ile mail alım ve gönderim işlemine başlayabilirsiniz.1.6KViews5likes0CommentsPowerShell ile Invoke-WebRequest işlemleri (tr-TR)
PowerShell ile Webde surf yapmaya hazır mısınız? PowerShell ile browser tadında bir surf keyfi için tanımanız gereken komut "Invoke-WebRequest" ta kendisidir. Invoke-WebRequest öncesi size basit bir PowerShell script ile dosya nasıl download edebilirsiniz göstermek isterim. $WebClient = New-Object System.Net.WebClient $WebClient.DownloadFile("http://<download linkinizi yazınız>","C:\dosya isminiz.formatı") Örneğin windows admin center indirmek istiyorsunuz. Link ve indirmek istediğiniz dizini belirterek download işlemini gerçekleştirebilirsiniz. Biz bu örneğimizde Windows Admin Center download linkini yazıyoruz ve C:\ dizininde oluşmasını istiyoruz. $WebClient = New-Object System.Net.WebClient $WebClient.DownloadFile("http://aka.ms/WACDownload","C:\wac.msi") Scrtipmizi çalıştırdıktan sonra mevcut uygulama çıktısı aşağıdaki gibidir. Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\Administrator> $WebClient = New-Object System.Net.WebClient PS C:\Users\Administrator> $WebClient.DownloadFile("http://aka.ms/WACDownload","C:\wac.msi") PS C:\Users\Administrator> cd.. PS C:\Users> cd.. PS C:\> dir Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 15.09.2018 10:19 PerfLogs d-r--- 16.05.2020 22:10 Program Files d----- 18.05.2020 15:32 Program Files (x86) d-r--- 9.05.2020 14:57 Users d----- 18.05.2020 11:30 Windows -a---- 18.05.2020 15:49 62980096 wac.msi PS C:\> Aynı süreci Invoke-WebRequest komutu ile gerçekleştirelim. daha basit şekilde işlemi halledelim yine bir önceki örneğimizde olduğu gibi indirme linkini ve indireceğimiz yeri belirliyoruz. Invoke-WebRequest -Uri "<download linkini giriniz>" -OutFile "C:\dosya adiniz.formati" Örnek Komutumuz ile MS SQL 2017 downlaod edelim. İndirme linkini ve indirmek istediğim dizini belirtiryorum. Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/?linkid=853017" -OutFile "C:\sql2017.exe" Uygulama çıktısı aşağıdaki gibidir. Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\Administrator> Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/?linkid=853017" -OutFile "C:\sql2017. exe" PS C:\Users\Administrator> cd.. PS C:\Users> cd.. PS C:\> dir Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 15.09.2018 10:19 PerfLogs d-r--- 16.05.2020 22:10 Program Files d----- 18.05.2020 15:32 Program Files (x86) d-r--- 9.05.2020 14:57 Users d----- 18.05.2020 11:30 Windows -a---- 18.05.2020 15:52 5325976 sql2017.exe -a---- 18.05.2020 15:49 62980096 wac.msi PS C:\> Invoke-WebRequest ile bir web sitenin içeriğini txt formatında dowload edebilirsiniz. Bu sefer biraz daha karmaşık bir komut hazırlıyoruz. Pipline kullanarak bir objenin içeriğini Invoke-WebRequest ile çağırıp daha sonra bu içeriği txt olarak çıktısını alıyoruz. Invoke-WebRequest "web adresi" | Select-Object -ExpandProperty Content | Out-File "C:\dosya ismi.txt" Örneğin emreozanmemis.com web sitesi için bu süreci uygulayalım. Invoke-WebRequest "http://emreozanmemis.com" | Select-Object -ExpandProperty Content | Out-Fi le "C:\emreozanmemis.txt" Uygulama çıktısı aşağıdaki gibidir. Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\Administrator> Invoke-WebRequest "http://emreozanmemis.com" | Select-Object -ExpandProperty Content | Out-Fi le "C:\emreozanmemis.txt" PS C:\Users\Administrator> cd.. PS C:\Users> cd.. PS C:\> dir Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 15.09.2018 10:19 PerfLogs d-r--- 16.05.2020 22:10 Program Files d----- 18.05.2020 15:32 Program Files (x86) d-r--- 9.05.2020 14:57 Users d----- 18.05.2020 11:30 Windows -a---- 18.05.2020 15:56 101964 emreozanmemis.txt -a---- 18.05.2020 15:52 5325976 sql2017.exe -a---- 18.05.2020 15:49 62980096 wac.msi PS C:\> Bu içeriği hiç indirmeden görüntülemek isterseniz de aşağıdaki komut işinizi fazlasıyla görecektir. Invoke-WebRequest "http://www.emreozanmemis.com" -OutFile "file" -PassThru | Select-Object -ExpandProperty Content Uygulama çıktısı Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\Administrator> Invoke-WebRequest "http://www.emreozanmemis.com" -OutFile "file" -PassThru | Select-Object -E xpandProperty Content <!DOCTYPE html> <html lang="tr" prefix="og: http://ogp.me/ns#"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <link rel="profile" href="http://gmpg.org/xfn/11"> <title>Emre Ozan Memis - Cloud and Datacenter Management</title> <style type="text/css"> body .primary-background, body button:hover, body button:focus, body input[type="button"]:hover, body input[type="reset"]:hover, body input[type="reset"]:focus, body input[type="submit"]:hover, body input[type="submit"]:focus, body .widget .social-widget-menu ul li, body .comments-area .comment-list .reply, body .slide-categories a:hover, body .slide-categories a:focus, body .widget .social-widget-menu ul li:hover a:before, body .widget .social-widget-menu ul li:focus a:before, body .ham, body .ham:before, body .ham:after, body .btn-load-more { background: #33363b; } body .secondary-background, body .wp-block-quote, body button, body input[type="button"], body input[type="reset"], body input[type="submit"], body .widget.widget_minimal_grid_tab_posts_widget ul.nav-tabs li.active a, body .widget.widget_minimal_grid_tab_posts_widget ul.nav-tabs > li > a:focus, body .widget.widget_minimal_grid_tab_posts_widget ul.nav-tabs > li > a:hover, body .author-info .author-social > a:hover, body .author-info .author-social > a:focus, body .widget .social-widget-menu ul li a:before, body .widget .social-widget-menu ul li:hover, body .widget .social-widget-menu ul li:focus, body .moretag, body .moretag,1.6KViews5likes0CommentsPowerShell ile Azure üzerinde RHEL VM olusturma (tr-TR)
Sabah ofisinize geldiniz ve x bir proje için acil VM ihtiyacı olduğu iş emri ile karşı karşıya kaldınız. Tüm bunlar için Azure portalına gir tek tek opsiyonları seç VM oluştur gibi süreçlerle uğraşmamak için siz kahvenizi hazırlarken VM kurulumu tamamlanmış olacak bir konudan bahsetmek istiyorum. Windows PowerShell üzerindne Azure portalınıza bağlantı sağlayıp aşağıdaki komut ile yeni bir kaynak grubu oluşturup içinde yeni bir sanal network ve RHEL kurulumunu 2-3 dakika içinde tamamlayabilirsiniz. New-AzResourceGroup -Name AzureRG -Location westus $gatewaysubnet = New-AzVirtualNetworkSubnetConfig -Name PSGatewaySubnet -AddressPrefix "10.102.100.0/27" $virtualNetwork = New-AzVirtualNetwork -Name PSAzureBCVnet -ResourceGroupName PSAzureBootCampRG -Location westus -AddressPrefix "10.102.100.0/24" -Subnet $gatewaysubnet Add-AzVirtualNetworkSubnetConfig -Name PSDMZSubnet -VirtualNetwork $virtualNetwork -AddressPrefix "10.102.100.96/27" $virtualNetwork | Set-AzVirtualNetwork $resourceGroup = "AzureRG" $location = "westus" $vmName = "PS-rhel2-vm" $cred = Get-Credential -Message "Enter a username and password for the virtual machine." New-AzResourceGroup -Name $resourceGroup -Location $location New-AzVM -ResourceGroupName $resourceGroup -Name $vmName -Location $location -ImageName "RHEL" -Size "Standard_D2_v3" -VirtualNetworkName "PSAzureBCVnet" -SubnetName "PSDMZSubnet" -Credential $cred -OpenPorts 22 Komutlar bütününü kendinize yada projelerinize göre özelleştirip kütüphanenizde bulundurmanız, bu tip durumlarda siz başka bir işiniz ile ilgilenirken size zaman kazandıracak ve işlerinizi kolaylaştıracaktır. Size ise 22 portundan SSH yapıp suncunun keyifine varmak kalır.1KViews5likes0CommentsPowerShell 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}942Views5likes0CommentsPowerShell ile WSUS Cleanup Wizard Script (tr-TR)
Aktif kullanılan WSUS serverlarda artan disk alanını kontrol altında tutmak ve kaynakları tasaruflu kullanmak için düzenli olarak temizlik yaparak eski süresi dolmuş yada kullanılmayan güncelleme paketlerini için aşağıdaki script kullanarak düzenleyebilir temizleyebilirsiniz. PowerShell açıp aşağıdaki script kopyala yapıştır ile çalıştırabilir ve ilgili update paketlerini temizleyerek disk kullanımınızı optimize ederbilirsiniz. # WSUSCleanupscript.ps1 [reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")` | out-null $wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer(); $cleanupScope = new-object Microsoft.UpdateServices.Administration.CleanupScope; $cleanupScope.DeclineSupersededUpdates = $true $cleanupScope.DeclineExpiredUpdates = $true $cleanupScope.CleanupObsoleteUpdates = $true $cleanupScope.CompressUpdates = $true $cleanupScope.CleanupObsoleteComputers = $true $cleanupScope.CleanupUnneededContentFiles = $true $cleanupManager = $wsus.GetCleanupManager(); $cleanupManager.PerformCleanup($cleanupScope); # Script END1.3KViews5likes0CommentsPowerShell ile WSUS kurulum ve yapılandırması (tr-TR)
Bu yazımda sizlere WSUS (Windows Server Update Services) bahsedeceğim. WSUS ile kendi yapınızda Windows serverlar için kendi update sunucunuzu yapılandırabilir ve bu sunucu üzerinden Microsoft ürünü kullandığınız işletim sistemlerini ve Microsoft yazılımlarını güncelleyebilirsiniz. PowerShell ile kurulum ve yapilandırmasını yapacağımız WSUS için detayları aşağıda bulabilirsiniz. Öncesinde bazı detaylardan bağsetmek isterim. WSUS normal şartlarda kolay kurulan ve yönetilen bir servistir ancak çok ilgi ister. Her gün kontrol edilmeli yada anlık olarak monitor edilmelidir. Günlük yayınlanan defender güncelllemeleri onaylanmalı yada otomatik olarak kurallaştırılarak onaylanması sağlanmalıdır. Aylık yayınlanan major ve minor Windows updateleri için incelemeler yapılmalı ve kontrollü bir şekilde uygulanmalıdır. Kurulum yapacağınız Windows Server domain join durumda yada workgroup olarak çalışan bir sunucu olabilir. Önerilen mimarilerde genelde Domain yapısında olması yönetim kolaylığı açısından tervcih edilemektedir. Ancak Workgroup olarakda sorunsuz çalışmaktadır. Kurulum için Windows Server işletim sistemimizde PowerShell'i administrator olarak çalıştırarak başlıyoruz. Install-WindowsFeature kurulum komutu ile iligli servisimiz WSUS için isim tanımlası ve yönetim araçlarını yüklemek için gerekli tanımlamaları aşağıdaki şekilde komutuma yazarak işlemlerime başlıyorum. Install-WindowsFeature UpdateServices -IncludeManagementTools Komut çıktısı: Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\Administrator> Install-WindowsFeature UpdateServices -IncludeManagementTools Success Restart Needed Exit Code Feature Result ------- -------------- --------- -------------- True No Success {ASP.NET 4.7, HTTP Activation, Remote Serv... WARNING: Additional configuration may be required. Review the article Managing WSUS Using PowerShell at TechNet Library (http://go.microsoft.com/fwlink/?LinkId=235499) for more information on the recommended steps to perform WSUS installation using PowerShell. Kurulum işlemimiz tamamlanmıştır. Yapılandırma işlemleri için aşağıdaki PowerShell scripti size yardımcı olacaktır. ### WUSUS post-deplpyment yapilandirma ayarlari . "C:\Program Files\Update Services\Tools\WsusUtil.exe" postinstall CONTENT_DIR=C:\WSUS ### WSUS nesnesinin tanımlanması $wsus = Get-WSUSServer ### WSUS yapilandirma tanimlamasi $wsusConfig = $wsus.GetConfiguration() ### Microsoft güncellemelerinin yapilandirilamsi Set-WsusServerSynchronization –SyncFromMU ### Güncelleme paketi dil tanımlaması sadece ingilizce yapilandirilmisiti bu bölümde istediğiniz dilleri virgul ekleyerek kısa kodunu yazabilirsiniz. $wsusConfig.AllUpdateLanguagesEnabled = $false $wsusConfig.SetEnabledUpdateLanguages("en") $wsusConfig.Save() ### WSUS ve Microsoft güncelleme SYNC tanimlamasi $wsus.GetSubscription().StartSynchronizationForCategoryOnly() start-sleep 15 ### SYNC tanimlamasi while ($wsus.GetSubscription().GetSynchronizationStatus() -ne "NotProcessing") { $time = get-date -UFormat "%H:%M:%S" $total = $wsus.GetSubscription().getsynchronizationprogress().totalitems $processed = $wsus.GetSubscription().getsynchronizationprogress().processeditems $process = $processed/$total $progress = "{0:P0}" -f $process Write-Host "" Write-Host "The first synchronization isn't completed yet $time" Write-Host "Kindly have patience, the progress is $progress" Start-Sleep 10 } Write-Host "The synchronization has completed at $time" -ForegroundColor Green Write-Host "The WSUS Configuration will now continue" -ForegroundColor Green ### Guncelleme urunlerinin tanimlanmasi, bu bolumu genisletebilrisiniz. Ben örnek için sadece Windows Server 2019 ekledim scritpti genisleterek diger urunleride ekleyebilirsiniz. write-host 'Setting WSUS Products' Get-WsusProduct | where-Object { $_.Product.Title -in ( 'Windows Server 2019') } | Set-WsusProduct ### Guncelleme sinfilarinin tanimlanmasi yine bu bolumde de siniflari arttirabilir yada azaltabilirsiniz. write-host 'Setting WSUS Classifications' Get-WsusClassification | Where-Object { $_.Classification.Title -in ( 'Critical Updates', 'Definition Updates', 'Feature Packs', 'Security Updates', 'Service Packs', 'Update Rollups', 'Updates') } | Set-WsusClassification ### SYNC yapilandirmasi write-host 'Enabling WSUS Automatic Synchronisation' $subscription = $wsus.GetSubscription() $subscription.SynchronizeAutomatically=$true ### otomatik sync yapilandirmasi $subscription.SynchronizeAutomaticallyTimeOfDay= (New-TimeSpan -Hours 0) $subscription.NumberOfSynchronizationsPerDay=1 $subscription.Save() ### Guncellenecek hedef grubun belirlenmesi $wsus.CreateComputerTargetGroup("Updates") ### Guncelleme paketlerinin onaylanmasi write-host 'Configuring default automatic approval rule' [void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") $rule = $wsus.GetInstallApprovalRules() | Where { $_.Name -eq "Default Automatic Approval Rule"} $class = $wsus.GetUpdateClassifications() | ? {$_.Title -In ( 'Critical Updates', 'Security Updates')} $class_coll = New-Object Microsoft.UpdateServices.Administration.UpdateClassificationCollection $class_coll.AddRange($class) $rule.SetUpdateClassifications($class_coll) $rule.Enabled = $True $rule.Save() ### Computer groupların güncelleme islemi $wsusConfig.OobeInitialized = $true $wsusConfig.Save() ### SYNC baslamasi $wsus.GetSubscription().StartSynchronization() Uygulama ekran görüntüleri: Windows Server Update Services açarsanız Overview ekranından yaptığımız işlemleri çapraz kontrolünü yapabilirsiniz. WSUS ile client ve server istemcilerinizi update etmek için; İstemcileri (Windows server işlerim sistemleri ve client işletim sistemlerini) WSUS'a ekleyerek güncellemelerini tek bir sunucu üzerinden kontrol ederek hangi sunucuda hangi güncelleme eksik yada hangi sunucunun güncellemeleri tamamlanmış görebiliyoruz. İstemci sistemi WSUS üzerinden güncellemek için aşağıdaki adımları yapmanız gerekmektedir. Bu işlemleri AD DS üzerinden policy olarak oluşturup tüm DC yapınızdaki bilgisayarları gruplayıp güncelleme servisini güncelleyebilirsiniz. Windows Update servisini WSUS üzerinde yapilandirmak için aşağıdaki işlemler iuygulayabilirsiniz. İlk olarak GPEDIT.msc (Local Group Policy Editor) gidiyoruz. Bu adımda WSUS sunucusuna istemciyi eklememiz için GPleri kullanıyoruz. Windows update server olarak WSUS'u göstereceğiz. Local Group Policy Editorumuz açıldığında aşağıdaki pencereyi görüntüleyeceksiniz. Local Computer Policy > Computer Configuration > Administrative Templates > Windows Components > Winows Update dizinine gidiyoruz. Windows Update Dizininde "Specify intranet Microsoft update service locaition" politikasını buluyoruz. Specify intranet Microsoft update service locaition çift tıklayara giriş yapıyoruz. Gördüğünüz gibi not configured şeklinde gözükmektedir. Bu politikayı aktif duruma getirmek için enabled konumuna getiriyoruz. Enabled ettikten sonra alt bölümde "set the intranet update service for detecting updates" ve "set the intranet statistics server" bölümlerine Vargonen olarak kullandığımız WSUS serverin bilgilerini giriyorsunuz. WSUS bilgisi: ht target=_blank target=_blank target=_blank target=_blanktp://192.168.2.212:8530 (işlem sürecinde wsus adresini FQDN olarak tanımlayıp gerekli dns yapılandırmasını yapıp kullanmanızı tavsiye ederim yarın IP adresini değiştirmek zorunda kalırsanız FQDN adresinin IP bilgisini değiştirmeniz yeterli olacaktır. .) Politikamızı aktif ettikten sonra aktif olduğunu kontrol etmek için Control Panel > Windows Update dizinine gidiniz. You receive updates: Managed by your system administrator şeklinde bir bölüm göreceksiniz. Bu WSUS üzerinden güncelleme aldığını gösteren bir uyardır. Özel durumlarda (Örneğin: WSUS çalışmadığında) "Check online for updates from Microsoft Update" linkine tıklayınız, güncellemeleriniz Microsoft update servisleri üzerinden online olarak indirilecektir. Güncellemeleri yüklemek ve kontrol etmek için check for updates linkine tıklayınız Çapraz kontrol için WSUS sunucusu üzerinden kontrol ediniz WSUS erişim bilgileriniz yok ise ilgili sistem yöneticinize başvurunuz. Sunucumuz başarı ile WSUS üzerine eklenmiş ve güncellemeleri tamamlanmış olduğunu göreceksiniz. Sunucunuz WSUS üzerinde gözükmüyor yada güncellemeleri yaptınız ve güncellemeler yüklü gözükmüyor ise aşağıdaki komutları çalıştırınız. Not: Komutlar komut satırı yada powershell de çalışmaktadır herhangi birinde bu işlemi gerçekleştirebilirsiniz. wuauclt.exe /resetauthorization /detectnow komutunu çalıştırıyoruz. wuauclt.exe /resetauthorization /detectnow İşle sonucu ekrana çıktı vermeyecektir. 5 dk sonra WSUS üzerinden tekrar kontrol ediniz. Kaynak: docs.microsoft.com Kaynak: spiceworks.com1.3KViews5likes0CommentsPowerShell ile aynı anda çok sayıda IP'ye ping atmak (tr-TR)
Toplu sunucu güncellemeleri yada bakımlarında suncunun up mı down mu kontrol etmek için hemen hemen herkesin ilk yaptığı işlemlerden olan "ping" atma süreci için gün geliyor aynı anda birden fazla ipye ping atmamız gerekiyor bunun için bir çok komut satırı açmak yerine basit bir script ile oluşturduğunuz ip listesini kullanarak toplu bir şekilde iplere ping atabilirsiniz. [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [string[]]$ComputerName, [Parameter(Position=1)] [int]$ResultCount = 150 ) $PipelineItems = @($input) if ($PipelineItems.Count) { $ComputerName = $PipelineItems } $ComputerName | Where-Object { -not ($_ -as [ipaddress]) } | ForEach-Object { $null = Resolve-DnsName $_ -ErrorAction Stop } $UseClearHostWhenRedrawing = $false try { [System.Console]::SetCursorPosition(0, 0) } catch [System.IO.IOException] { $UseClearHostWhenRedrawing = $true } Clear-Host [array]$PingData = foreach($Computer in $ComputerName) { @{ 'Name' = $Computer 'Pinger' = New-Object -TypeName System.Net.NetworkInformation.Ping 'Results' = New-Object -TypeName System.Collections.Queue($ResultCount) 'LastResult' = @{} } } foreach ($Item in $PingData) { for ($Filler = 0; $Filler -lt $ResultCount; $Filler++) { $Item.Results.Enqueue('_') } } while ($true) { [array]$PingTasks = foreach($Item in $PingData) { $Item.Pinger.SendPingAsync($Item.Name) } try { [Threading.Tasks.Task]::WaitAll($PingTasks) } catch [AggregateException] { } 0..($PingTasks.Count-1) | ForEach-Object { $Task = $PingTasks[$_] $ComputerData = $PingData[$_] if ($Task.Status -ne 'RanToCompletion') { $ComputerData.Results.Enqueue('?') } else { $ComputerData.LastResult = $Task.Result switch ($Task.Result.Status) { 'Success' { $ComputerData.Results.Enqueue('.') } 'TimedOut' { $ComputerData.Results.Enqueue('x') } } } } foreach ($Item in $PingData) { while ($Item.Results.Count -gt $ResultCount) { $null = $Item.Results.DeQueue() } } if ($UseClearHostWhenRedrawing) { Clear-Host } else { $CursorPosition = $Host.UI.RawUI.CursorPosition $CursorPosition.X = 0 $CursorPosition.Y = 0 $Host.UI.RawUI.CursorPosition = $CursorPosition } foreach ($Item in $PingData) { Write-Host (($Item.Results -join '') + ' | ') -NoNewline $PingText = if ($Item.LastResult.Status -eq 'Success') { if (1000 -le $Item.LastResult.RoundTripTime) { '(999+ms)' } else { '({0}ms)' -f $Item.LastResult.RoundTripTime.ToString().PadLeft(4, ' ') } } else { '(----ms)' } Write-Host "$PingText | " -NoNewline if ($Item.LastResult.Status -eq 'Success') { Write-Host ($Item.Name) -BackgroundColor DarkGreen } else { Write-Host ($Item.Name) -BackgroundColor DarkRed } } $Delay = 1000 - ($PingData.lastresult.roundtriptime | Sort-Object | Select-Object -Last 1) Start-Sleep -MilliSeconds $Delay } Scriptinizi PS1 dosyası olarak oluşturun ve PowerShell komut satırından Get-Content ile ip listenizi ve PS1 dosyanızı çalıştırınız. Get-Content .\iplist.txt | .\ping.ps1 Uygulama çıktısı aşağıdaki gibidir. __________________________________________________________............................................................................................ | ( 0ms) | 192.18.101.130 ______________________________________________________________________________________________________________________________________________________ | (----ms) | 192.18.101.126 __________________________________________________________............................................................................................ | ( 0ms) | 192.18.101.135 PS C:\Users\Administrator\desktop> PS C:\Users\Administrator\desktop> Get-Content .\iplist.txt | .\ping.ps13.2KViews5likes0CommentsPowerShell ile Hyper-V üzerinde VM oluşturma (tr-TR)
Windows Server 2019, Windows Server 2016 ve Windows Server 2012 işletim sistemlerinde kullanabileceğiniz Hyper-V üzerinde VM oluşturma scrpiti ile hızlı ve pratik şekilde arka arkaya vm oluşturabilirsiniz. VM ismi, VM yeri ve ISO path tanımlamaları ile başlayacağınız işleme son olarak oluşacak olan VM CPU RAM ve DISK kaynaklarını belirterek VM oluşturma işlemine başlayabilirsiniz. İlgili scripti Hyper-V yapınıza göre düzenledikten sonra PowerShell komut ekranınıza yapıştırabilir yada ps1 dosyası oluşturarak kahveniz yudumlarkene vmlerinizi oluşturabilirsiniz. # Bu script Hyper-V vm oluşturmak icin düzenlenmiştir. #VM isimlerini okuyacagi dosya tanimlamasini yapiniz. Birden fazla isim tanımlayarak aynı anda birden fazla VM kurulumu gerçekleştirebilirsiniz. $VMismi = Get-Content (Read-Host "VM isimleri olan dosyanın path giriniz.") #Kurulum yapacaginiz isletim sistemi ISOsunu tanimlayiniz. $ISOpath = Read-Host "ISOnuzun bulundugu dosyanın path giriniz." #VM diskinin olusacagi path belirtiniz. $VMyeri = "$Home\Hyper-V\Virtural Machines" #Virtual switch olusturup adini ve turunu belirleiyin. New-VMSwitch -Name "PrivateNetwork" -SwitchType Private $VMNet = "PrivateNetwork" #VM olusturmak icin disk size, memory size ve pathleri tanimlayiniz. Foreach($vm in $VMismi) { New-VM -Name $VM -Generation 2 -SwitchName $VMNet New-VHD -Path "$VMyeri\$VM\$vm.vhdx" -Dynamic -SizeBytes 40GB ADD-VMHardDiskDrive -VMismi $vm -Path "$VMLOC\$VM\$vm.vhdx" Set-VM $VM -MemoryMinimumBytes 1GB Add-VMDvdDrive -VMismi $vm -Path $ISOpath }879Views5likes0CommentsPowerShell ile Anlık CPU, RAM ve Disk Kullanımı İzleme (tr-TR)
Windows Server Core kullananların çok işine yarayacak olan bu script sayesinde CPU, Ram ve Disk kullanımlarınızı anlık olarak görüntüleyebilirsiniz. PowerShell ile bir çok veriyi size tek satırda sunan bu script sayesinde kaynak kullanımlarınızı anlık izleyerek optimize edebilirsiniz. while($true) { $ComputerCPU = (Get-WmiObject -Class win32_processor -ErrorAction Stop | Measure-Object -Property LoadPercentage -Average | Select-Object Average).Average $ComputerMemory = Get-WmiObject -Class win32_operatingsystem -ErrorAction Stop $UsedMemory = $ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory $Memory = (($UsedMemory/ $ComputerMemory.TotalVisibleMemorySize)*100) $RoundMemory = [math]::Round($Memory, 2) #$disk = Get-PSDrive C | Select-Object Used,Free $TotalDisk = Get-WMIObject Win32_LogicalDisk -Filter "DeviceID='C:'" | ForEach-Object {[math]::truncate($_.Size / 1GB)} $FreeSpace = Get-WMIObject Win32_LogicalDisk -Filter "DeviceID='C:'" | ForEach-Object {[math]::truncate($_.freespace / 1GB)} $Date = Get-Date -DisplayHint Date -Format MM/dd/yyyy $Time = Get-Date -DisplayHint Time -Format HH:mm:ss Write-Host "Date: " $Date " Time: " $Time " CPU: " $ComputerCPU " Memory: " $RoundMemory " Free Space: " $Freespace " Total Size : " $TotalDisk sleep 2 } Uygulama çıktısı aşağıdaki gibidir. PS C:\Users\Administrator\desktop> .\PSkaynakmonitor.ps1 Date: 04/10/2019 Time: 17:45:16 CPU: 1 Memory: 19.25 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:45:22 CPU: 1.75 Memory: 19.31 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:45:29 CPU: 12.75 Memory: 19.26 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:45:35 CPU: 0.75 Memory: 19.26 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:45:42 CPU: 1.25 Memory: 19.26 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:45:48 CPU: 0.75 Memory: 19.26 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:45:54 CPU: 0.75 Memory: 19.25 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:46:01 CPU: 1 Memory: 19.25 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:46:07 CPU: 1 Memory: 19.26 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:46:14 CPU: 0.75 Memory: 19.25 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:46:20 CPU: 3.25 Memory: 19.25 Free Space: 23 Total Size : 59 Date: 04/10/2019 Time: 17:46:27 CPU: 11.5 Memory: 19.25 Free Space: 23 Total Size : 593.2KViews5likes1Comment
Events
Recent Blogs
- One new resource, logging improvements and bugfixes. This is what SharePointDsc v5.2 is bringing to the table!May 12, 20227.5KViews1like0Comments
- 2 MIN READThis article describes a solution of an issue I have been troubleshooting today, where switching to an AllSigned execution policy resulted in the "This publisher is explicitly not trusted on your sys...Mar 18, 20226.4KViews1like1Comment