Microsoft MVP Summit – March 2026

Just wrapped up an incredible week at the Microsoft MVP Summit in Redmond, USA
It was a truly inspiring experience packed with deep technical sessions, insightful discussions with Microsoft product groups, and meaningful conversations with fellow MVPs from around the world. These moments are always a great reminder of the strength of this amazing global community and the impact we can create together.

One of the highlights for me was having the privilege to record a session at the DevRel Studios (formerly known as Channel 9 Studios) alongside my fellow MVP Barış Kanlıca, a fantastic experience I won’t forget anytime soon!
A special thank you to the amazing DevRel Studios team for their warm welcome, hospitality, and outstanding support throughout the entire experience 🙌
Also, a big thank you to the Microsoft product groups, as well as the Global and Regional MVP Program teams, for their openness, engagement, and continued support of the community.

Feeling grateful, energized, and excited to bring back new ideas, knowledge, and perspectives to share with the community.

special thanks to with Baris KANLICA and Fatih Demirci

Continue Reading Microsoft MVP Summit – March 2026

PowerShell ile Azure AI Content Safety Moderasyon

Azure AI Content Safety, zararlı içerikleri tespit etmek için gelişmiş AI modelleri kullanır. PowerShell ile metin ve görüntü moderasyonunu uygulamalarınıza entegre edebilirsiniz.

Content Safety Servisi Oluşturmak

PowerShell

$rg       = "newrg-"
$csName   = "myContentSafety"
$location = "uksouth"
 
New-AzCognitiveServicesAccount -ResourceGroupName $rg -Name $csName `
    -Type ContentSafety -SkuName S0 -Location $location
 
$apiKey = (Get-AzCognitiveServicesAccountKey -ResourceGroupName $rg -Name $csName).Key1
Write-Host "Content Safety servisi hazır."
 

Metin Moderasyonu Yapmak

PowerShell

$endpoint = "https://mycontentsafety-26e9d.cognitiveservices.azure.com/contentsafety/text:analyze?api-version=2024-09-01"
$headers  = @{ "Ocp-Apim-Subscription-Key" = $apiKey; "Content-Type" = "application/json" }
 
function Test-ContentSafety {
    param([string]$Text)
    $body = @{
        text       = "$text"
        categories = @("Hate","SelfHarm","Sexual","Violence")
        outputType = "FourSeverityLevels"
    } | ConvertTo-Json
    
    $result = Invoke-RestMethod -Uri $endpoint -Method Post -Headers $headers -Body $body
    return $result.categoriesAnalysis
}
 
$analysis = Test-ContentSafety -Text "Bu bir test mesajıdır."
$analysis | ForEach-Object {
    $safe = $_.severity -eq 0
    $color = if ($safe) { "Green" } else { "Red" }
    Write-Host "$($_.category): Seviye $($_.severity)" -ForegroundColor $color
}
 

test 1

test 2

Continue Reading PowerShell ile Azure AI Content Safety Moderasyon

Had a fantastic time at DevRel Studios of Microsoft in Redmond

One of the highlights for me was having the privilege to record a session at the DevRel Studios (formerly known as Channel 9 Studios) alongside my fellow MVP Barış Kanlıca, a fantastic experience I won’t forget anytime soon!
A special thank you to the amazing DevRel Studios team for their warm welcome, hospitality, and outstanding support throughout the entire experience 🙌
Also, a big thank you to the Microsoft product groups, as well as the Global and Regional MVP Program teams, for their openness, engagement, and continued support of the community.

link for the edited video will be back in here soon..

Continue Reading Had a fantastic time at DevRel Studios of Microsoft in Redmond

PowerShell ile Azure Maps Konum Servisleri Kullanımı

Azure Maps, harita, konum ve coğrafi analiz servisleri sunar. PowerShell ile adresi koordinata dönüştürme, mesafe hesaplama ve ısı haritası verisi üretme gibi görevleri otomatize edebilirsiniz.

Azure Maps Hesabı Oluşturmak

PowerShell

$rg        = "newrg-"
$mapsName  = "myAzureMaps"
$location  = "global"
 
New-AzMapsAccount -ResourceGroupName $rg -Name $mapsName `
    -Location $location -SkuName G2
 
$key = (Get-AzMapsAccountKey -ResourceGroupName $rg -Name $mapsName).PrimaryKey
Write-Host "Azure Maps hazır. Anahtar: $($key.Substring(0,15))..."
 

Adres Geocoding

PowerShell

$address = "10 Downing Street, London, UK"
$url     = "https://atlas.microsoft.com/search/address/json?api-version=1.0&subscription-key=$key&query=$([Uri]::EscapeDataString($address))"
 
$result  = Invoke-RestMethod -Uri $url -Method Get
$best    = $result.results[0]
 
Write-Host "Adres: $($best.address.freeformAddress)"
Write-Host "Koordinat: $($best.position.lat), $($best.position.lon)"

 

İki Nokta Arası Mesafe Hesaplamak

PowerShell

$origin = "51.5074,-0.1278"  # Londra
$dest   = "51.4779,-0.0015"  # Greenwich
 
$routeUrl = "https://atlas.microsoft.com/route/directions/json?api-version=1.0&subscription-key=$key&query=$($origin):$($dest)"
$route = Invoke-RestMethod -Uri $routeUrl -Method Get
 
$summary = $route.routes[0].summary
Write-Host "Mesafe: $([math]::Round($summary.lengthInMeters / 1000, 2)) km"
Write-Host "Tahmini süre: $([math]::Round($summary.travelTimeInSeconds / 60, 0)) dakika"
 

Continue Reading PowerShell ile Azure Maps Konum Servisleri Kullanımı

PowerShell ile Azure Subscription Taşıma ve Yeniden Düzenleme

Büyüyen Azure ortamlarında abonelik organizasyonunu yeniden düzenlemek kaçınılmaz olabilir. PowerShell ile Management Group hiyerarşisini yapılandırabilir ve kaynakları taşıyabilirsiniz.

Management Group Hiyerarşisini Görmek

PowerShell
 
#updated
Get-AzManagementGroupEntity | select type, DisplayName, ParentDisplayNameChain 

Management Group Oluşturmak ve Abonelik Taşımak

PowerShell

New-AzManagementGroup -GroupId "web-workloads" -DisplayName "Production Workloads"

$subId = (Get-AzSubscription -SubscriptionName "www").Id
 
New-AzManagementGroupSubscription `
    -GroupId "web-workloads" `
    -SubscriptionId $subId
 
Write-Host "Abonelik taşındı: Production-01 -> web-workloads" -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Subscription Taşıma ve Yeniden Düzenleme

PowerShell ile Azure Load Testing Servisi Yönetimi – Part 1

Azure Load Testing, uygulamalarınızın yük altındaki performansını ölçmek için Apache JMeter tabanlı yük testleri çalıştırır. PowerShell ile test koşularını otomatize edebilir ve sonuçları analiz edebilirsiniz.

Load Testing Resource Oluşturmak

PowerShell
$rg       = "newrg-"
$ltName   = "myLoadTesting"
$location = "uksouth"
 
New-AzLoad -ResourceGroupName $rg -Name $ltName `
    -Location $location -warningaction silentlycontinue
 
Write-Host "Load resource olusturuldu." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Load Testing Servisi Yönetimi – Part 1

PowerShell ile Azure Bastion Yönetimi ve Güvenli VM Erişimi

Azure Bastion, VM’lerinize public IP kullanmadan güvenli RDP/SSH erişimi sağlar. PowerShell ile Bastion host’larını oluşturabilir ve yönetebilirsiniz.

Bastion Host Oluşturmak

PowerShell

$rg       = "vpntest"
$vnetName = "vpntest-vnet"
$location = "eastus"
 
$vnet   = Get-AzVirtualNetwork -ResourceGroupName "vpntest" -Name $vnetName
$subnet = Add-AzVirtualNetworkSubnetConfig -Name "AzureBastionSubnet" `
    -VirtualNetwork $vnet -AddressPrefix "20.0.10.0/24"
$vnet | Set-AzVirtualNetwork | Out-Null
 
$publicIP = New-AzPublicIpAddress -ResourceGroupName $rg -Name "bastion-ip" `
    -Location $location -AllocationMethod Static -Sku Standard
 
New-AzBastion -ResourceGroupName $rg -Name "OnurBastion" `
    -PublicIpAddressRgName $rg -PublicIpAddressName "bastion-ip" `
    -VirtualNetworkRgName "vpntest" -VirtualNetworkName $vnetName `
    -Sku Standard
Write-Host "Bastion Host hazır." -ForegroundColor Green
 

Bastion Durum Bilgisini Almak

PowerShell

$bastion = Get-AzBastion -ResourceGroupName $rg -Name "onurbastion"
Write-Host "Bastion Durumu: $($bastion.ProvisioningState)"
Write-Host "SKU: $($bastion.Sku.Name)"
 

Continue Reading PowerShell ile Azure Bastion Yönetimi ve Güvenli VM Erişimi

PowerShell ile Azure Key Vault Sertifika Yönetimi

TLS/SSL sertifikalarının yönetimi, kurumsal ortamlarda kritik önem taşır. Azure Key Vault sertifika yönetimini PowerShell ile otomatize ederek sertifika yenileme ve dağıtım süreçlerini kolaylaştırabilirsiniz.

Key Vault’ta Sertifika Oluşturmak

PowerShell

$vaultName = "ml012437143227"
 
$certPolicy = New-AzKeyVaultCertificatePolicy `
    -SubjectName "CN=app.bakionur.com" `    -IssuerName Self `
    -SecretContentType "application/x-pkcs12" `
    -ValidityInMonths 12 `
    -KeyType RSA `
    -KeySize 2048 `
    -RenewAtPercentageLifetime 80
 
Add-AzKeyVaultCertificate `
    -VaultName $vaultName `
    -Name "app-bakionur-cert" `
    -CertificatePolicy $certPolicy
 
Write-Host "Sertifika olusturma baslatıldı..." -ForegroundColor Yellow
 
# Tamamlanmasını bekle
do {
    Start-Sleep -Seconds 10
    $cert = Get-AzKeyVaultCertificate -VaultName $vaultName -Name "app-bakionur-cert"
} until ($cert -ne $null)
 
Write-Host "Sertifika hazır. Parmak izi: $($cert.Thumbprint)" -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Key Vault Sertifika Yönetimi

PowerShell ile Azure Container Apps Yönetimi

Azure Container Apps, container’ları serverless bir ortamda çalıştırmanın en kolay yolunu sunar. PowerShell ile container app’leri oluşturabilir, ölçekleyebilir ve izleyebilirsiniz.

Container Apps Ortamı Oluşturmak

PowerShell

$rg       = "newrg-"
$location = "eastus"
$envName  = "onurenv"
 
New-AzOperationalInsightsWorkspace -ResourceGroupName $rg -Name workspace-azpstestgp -Sku PerGB2018 -Location canadacentral -PublicNetworkAccessForIngestion "Enabled" -PublicNetworkAccessForQuery "Enabled"

$CustomId = (Get-AzOperationalInsightsWorkspace -ResourceGroupName $rg -Name workspace-azpstestgp).CustomerId
$SharedKey = (Get-AzOperationalInsightsWorkspaceSharedKey -ResourceGroupName $rg -Name workspace-azpstestgp).PrimarySharedKey
$workloadProfile = New-AzContainerAppWorkloadProfileObject -Name "Consumption" -Type "Consumption"

New-AzContainerAppManagedEnv -Name azps-env -ResourceGroupName $rg-Location eastus -AppLogConfigurationDestination "log-analytics" -LogAnalyticConfigurationCustomerId $CustomId -LogAnalyticConfigurationSharedKey $SharedKey -VnetConfigurationInternal:$false -WorkloadProfile $workloadProfile

Container App Dağıtmak

PowerShell

$appName = "onurapi1"
 
New-AzContainerApp `
    -ResourceGroupName $rg `
    -Name $appName `
    -Location $location `
    -EnvironmentId (Get-AzContainerAppManagedEnv -ResourceGroupName $rg -Name "azps-env").Id `
    -TemplateContainer @(
        @{
            Name  = "api-container"
            Image = "mcr.microsoft.com/dotnet/samples:aspnetapp"
            Resources = @{ Cpu = 0.25; Memory = "0.5Gi" }
        }
    ) `
    -ScaleMinReplica 0 `
    -ScaleMaxReplica 5
 
$app = Get-AzContainerApp -ResourceGroupName $rg -Name $appName
$app

Continue Reading PowerShell ile Azure Container Apps Yönetimi

PowerShell ile Azure Consumption API ile Detaylı Fatura Analizi

Azure Consumption API, kaynak bazında ayrıntılı maliyet ve kullanım verisi sunar. PowerShell ile bu veriyi çekerek FinOps raporları, bölüm bazında geri ödeme (chargeback) hesaplamaları yapabilirsiniz.

Kullanım Detaylarını Almak

PowerShell

$subscriptionId = (Get-AzContext).Subscription.Id
$token   = (Get-AzAccessToken).Token
$token = ConvertFrom-SecureString -SecureString $Token -AsPlainText

$headers = @{ Authorization = "Bearer $token" }
 
$startDate = (Get-Date -Day 1).ToString("yyyy-MM-dd")
$endDate   = (Get-Date).ToString("yyyy-MM-dd")
 
$usageUrl = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Consumption/usageDetails?api-version=2023-05-01&startDate=$startDate&endDate=$endDate&metric=ActualCost&top=1000"
 
$allUsage = @()
do {
    $resp = Invoke-RestMethod -Uri $usageUrl -Headers $headers
    $allUsage += $resp.value
    $usageUrl = $resp.nextLink
    Write-Host "Alinan kayıt: $($allUsage.Count)"
} while ($usageUrl)
 
Write-Host "Toplam kullanım kaydı: $($allUsage.Count)" -ForegroundColor Green
 

Departman Bazında Chargeback Raporu

PowerShell

$chargebacks = $allUsage | Group-Object { $_.tags.Department } | ForEach-Object {
    $dept = if ($_.Name) { $_.Name } else { "Etiketlenmemis" }
    [PSCustomObject]@{
        Departman   = $dept
        ToplamMaliyet = [math]::Round(($_.Group.properties.costInBillingCurrency | Measure-Object -Sum).Sum, 2)
        KaynakSayisi = ($_.Group | Select-Object -ExpandProperty id -Unique).Count
        ParaBirimi  = $_.Group[0].properties.billingCurrencyCode
    }
}
 
$chargebacks | Sort-Object ToplamMaliyet -Descending | Format-Table -AutoSize
$chargebacks | Export-Csv "chargeback_$(Get-Date -Format 'yyyyMM').csv" -NoTypeInformation
Write-Host "Chargeback raporu hazırlandı." -ForegroundColor Cyan
 

Continue Reading PowerShell ile Azure Consumption API ile Detaylı Fatura Analizi

PowerShell ile Azure AI Search Index Oluşturma ve Sorgulama

Azure AI Search uygulamalarınıza kurumsal düzeyde arama kapasitesi ekler. PowerShell ile index oluşturabilir, belge yükleyebilir ve arama sorgularını test edebilirsiniz.

Search Service Oluşturmak

PowerShell
New-AzSearchService -ResourceGroupName "newrg-" -Name "myaisearchonur" `
    -Sku "Standard" -Location "uksouth" -PartitionCount 1 -ReplicaCount 1
 
$adminKey = (Get-AzSearchAdminKeyPair -ResourceGroupName "newrg-" -ServiceName "myaisearchonur").Primary
Write-Host "Search Service olusturuldu. Admin Key: $adminKey"
 

Index Oluşturmak

PowerShell

$endpoint  = "https://myaisearchonur.search.windows.net"
$headers   = @{ "api-key" = $adminKey; "Content-Type" = "application/json" }
$indexBody = @{
    name = "articles-index"
    fields = @(
        @{ name = "id";       type = "Edm.String"; key = $true }
        @{ name = "title";    type = "Edm.String"; searchable = $true }
        @{ name = "content";  type = "Edm.String"; searchable = $true }
        @{ name = "category"; type = "Edm.String"; filterable = $true }
    )
} | ConvertTo-Json -Depth 5
 
Invoke-RestMethod -Uri "$endpoint/indexes/articles-index?api-version=2023-11-01" `
    -Headers $headers -Method Put -Body $indexBody
Write-Host "Index olusturuldu." -ForegroundColor Green
 

Belge Yüklemek ve Arama Yapmak

PowerShell

$docs = @{ value = @(@{ "@search.action" = "upload"; id = "1"; title = "Azure AI ile PowerShell"; content = "Azure AI Foundry ve PowerShell ile denemeler yapmak by Baki Onur Okutucu – Microsoft MVP"; category = "Azure AI" }) } | ConvertTo-Json -Depth 5
Invoke-RestMethod -Uri "$endpoint/indexes/articles-index/docs/index?api-version=2023-11-01" `
    -Headers $headers -Method Post -Body $docs
 
$results = Invoke-RestMethod -Uri "$endpoint/indexes/articles-index/docs?search=PowerShell&top=5&api-version=2023-11-01" `
    -Headers $headers -Method Get
$results.value | Select-Object title, category | Format-Table
Write-Host "Arama tamamlandı. $($results.count) sonuç." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure AI Search Index Oluşturma ve Sorgulama

AgentCon Istanbul

36 ülkede düzenlenen global AgentCon serisinin İstanbul ayağı olan AgentCon Istanbul’da konuşmacı olarak yer almaktan büyük onur duydum.

Etkinliğe ev sahipliği yapan Nişantaşı Üniversitesi’ne, AI ve yazılım topluluğuna kapılarını açtikleri için özellikle teşekkür etmek isterim. Mekân, atmosfer ve salondaki enerji gerçekten çok özeldi.

En çok etkileyen şey ise öğrencilerin ve genç profesyonellerin yüksek katılımı ve ilgisiydi. Agentic AI alanında kendini geliştiren, sorgulayan ve geleceği şekillendirmeye hazırlanan genç zihinlerle bir arada olmak ilham vericiydi. Sorular, oturum araları sohbetleri ve fikir alışverişleri en az sunumlar kadar değerliydi.

Birbirinden değerli konuşmacılarla aynı sahneyi paylaşmak da ayrıca mutluluk vericiydi.

Bu güzel organizasyonu mümkün kılan tüm organizasyon ekibine, öğrenci topluluklarına, gönüllülere, Microsoft’a ve katkı sağlayan tüm paydaşlara teşekkür ederim. Bu tür etkinlikler ancak güçlü bir topluluk ruhuyla gerçekleşebiliyor.

AgentCon bize bir kez daha gösterdi ki; AI sadece teknoloji değil, aynı zamanda iş birliği, paylaşım ve birlikte üretme kültürüdür.
Bir sonraki AgentCon durağında görüşmek üzere!

I had the honour of speaking at AgentCon Istanbul, the Istanbul leg of the global AgentCon series taking place across 36 countries worldwide.

This special edition was hosted at Nişantaşı University, and I would like to sincerely thank the university for opening its doors to the AI and developer community. The venue, the atmosphere, and the energy in the room made the entire experience even more memorable.



What truly stood out was the incredible engagement from students and young professionals. Being surrounded by brilliant, curious, forward-thinking minds who are actively exploring Agentic AI was inspiring. The questions, discussions, and hallway conversations reminded me once again that the future of AI is in very capable hands.

Continue Reading AgentCon Istanbul

PowerShell ile Azure Kubernetes Fleet Yönetimi

Azure Kubernetes Fleet Manager, birden fazla AKS kümesini merkezi olarak yönetmenizi sağlar. PowerShell ile fleet oluşturabilir, üye kümeler ekleyebilir ve tüm fleet genelinde güncellemeler uygulayabilirsiniz.

Kubernetes Fleet Oluşturmak

PowerShell
$rg         = "newrg-"
$location   = "uksouth"
$fleetName  = "towershellfleet01"
 
New-AzFleet -ResourceGroupName $rg -Name $fleetName -Location $location
Write-Host "Kubernetes Fleet olusturuldu." -ForegroundColor Green
 

AKS Kümelerini Fleet’e Eklemek

PowerShell

$clusters = @("aks")
 
foreach ($cluster in $clusters) {
    $aksId = (Get-AzAksCluster -ResourceGroupName "vpntest" -Name $cluster).Id
    
    New-AzFleetMember -ResourceGroupName $rg -FleetName $fleetName `
        -Name $cluster `
        -ClusterResourceId $aksId
    
    Write-Host "Fleet üyesi eklendi: $cluster" -ForegroundColor Green
}
 

Continue Reading PowerShell ile Azure Kubernetes Fleet Yönetimi

PowerShell ile Özel Azure Policy Definition Yazma ve Test Etme

Hazır Azure politikaları bazen iş gereksinimlerini tam olarak karşılamayabilir. PowerShell ile kuruluşunuza özel politika tanımları yazabilir, birim testleri uygulayabilir ve dağıtabilirsiniz.

Özel Policy Tanımı Yazmak

PowerShell

$policyRule = @{
    if = @{
        allOf = @(
            @{ field = "type"; equals = "Microsoft.Storage/storageAccounts" }
            @{ field = "Microsoft.Storage/storageAccounts/allowBlobPublicAccess"; notEquals = $false }
        )
    }
    then = @{ effect = "Deny" }
}
 
$policyDef = New-AzPolicyDefinition `
    -Name "deny-storage-public-blob-access" `
    -DisplayName "Storage hesaplarında genel Blob erişimini engelle" `
    -Description "Tüm storage hesaplarının AllowBlobPublicAccess özelliğini False olarak zorunlu kılar." `
    -Policy ($policyRule | ConvertTo-Json -Depth 10) `
    -Mode All `
    -Metadata (@{ category = "Storage"; version = "1.0.0" } | ConvertTo-Json)
 
Write-Host "Özel politika tanımı olusturuldu: $($policyDef.Name)" -ForegroundColor Green
 

Polici’yi Test Etmek

PowerShell

# What-If ile mevcut kaynakları test et
$scope = "/subscriptions/$($(Get-AzContext).Subscription.Id)"
 
New-AzPolicyAssignment -Name "test-deny-public-blob" `
    -PolicyDefinition $policyDef -Scope $scope
 
# Uyumluluk değerlendirmesini başlat
Start-AzPolicyComplianceScan -AsJob
 
Start-Sleep -Seconds 30
 
$nonCompliant = Get-AzPolicyState `
    -PolicyDefinitionName "deny-storage-public-blob-access" `
    -Filter "ComplianceState eq 'NonCompliant'"
 
Write-Host "Uyumsuz storage hesabı: $($nonCompliant.Count)" -ForegroundColor Yellow
$nonCompliant | Select-Object ResourceName, ResourceGroup | Format-Table
 

Continue Reading PowerShell ile Özel Azure Policy Definition Yazma ve Test Etme

AgentCon Istanbul

Excited to be speaking at AgentCon Istanbul next week.

I’ll be delivering a session on “Building External MCP Servers with Azure Functions”, where we’ll explore how to design and expose MCP-compliant external services using Azure Functions, covering architecture patterns, real-world use cases, and practical implementation tips.

📅 When: Saturday, 7 February 2026
📍 Where: Nișantaşı Üniversitesi NeoTech Kampüs, Sarıyer / Istanbul

Huge thanks to the Global AI Community, Microsoft, and Nișantaşı University for making this event possible.
Looking forward to great conversations, hands-on discussions, and meeting the AI & cloud community in Istanbul!

See the full program and register: agentcon.city/istanbul

Continue Reading AgentCon Istanbul

 Cloud Tech Tallinn 2026 (CTTT26)

Great to be in Tallinn, Estonia for Cloud Tech Tallinn 2026 (CTTT26) 🇪🇪

I really enjoyed delivering my session on “Building External MCP Servers using Azure Functions” and discussing practical approaches to building scalable, cloud-native MCP architectures.

Huge thanks to the CTTT26 organizing team and everyone who attended. The questions and conversations made it a great experience.

Looking forward to continuing these discussions.

Continue Reading  Cloud Tech Tallinn 2026 (CTTT26)

Microsoft AI Tour, New York City

It was lovely being part of Microsoft AI Tour, New York City last week.

It was a real pleasure engaging with so many curious, thoughtful attendees and diving into great conversations around Azure AI Foundry and the Foundry Agent Service. From architecture patterns to real-world adoption questions, the level of curiosity throughout the conference was inspiring.

I genuinely enjoyed answering questions, exchanging ideas, and seeing how teams are thinking about building responsible, scalable AI solutions on Azure.

Big thanks to the organizers for a fantastic event and to everyone who stopped by to ask questions, challenge ideas, and share their experiences. These interactions are what make community events like this so valuable.

Looking forward to what’s next!

Continue Reading Microsoft AI Tour, New York City

PowerShell ile Otomatik Kaynak Raporu Üretimi

Azure ortamınızı düzenli olarak Word veya HTML formatında belgelemek, hem operasyonel görünürlük hem de denetim gereksinimleri için kritiktir. PowerShell ile bu raporu tamamen otomatize edebilirsiniz.

Azure Ortam Envanterini Toplamak

PowerShell

Connect-AzAccount
 
$report = [PSCustomObject]@{
    Abonelik     = (Get-AzContext).Subscription.Name
    VMSayisi     = (Get-AzVM).Count
    StorageSayisi= (Get-AzStorageAccount).Count
    VNetSayisi   = (Get-AzVirtualNetwork).Count
    NSGSayisi    = (Get-AzNetworkSecurityGroup).Count
    KeyVaultSayisi = (Get-AzKeyVault).Count
    AktifAlert   = (Get-AzMetricAlertRuleV2 | Where-Object { $_.Enabled }).Count
}
 
Write-Host "Envanter toplama tamamlandı."
$report | Format-List

HTML Raporu Oluşturmak

PowerShell

$htmlReport = @"
<!DOCTYPE html>
<html><head><title>Azure Ortam Raporu</title>
<style>body{font-family:Arial;margin:20px} h1{color:#1F4E79} table{border-collapse:collapse;width:100%}
th,td{border:1px solid #ddd;padding:8px;text-align:left} tr:nth-child(even){background:#f2f2f2}
.ok{color:green} .warn{color:orange}</style></head><body>
<h1>Azure Ortam Raporu- Tets- TowerShell </h1>
<h2>Özet</h2>
<table>
<tr><th>Kaynak</th><th>Sayı</th></tr>
<tr><td>Sanal Makine</td><td class='ok'>$($report.VMSayisi)</td></tr>
<tr><td>Depolama Hesabı</td><td>$($report.StorageSayisi)</td></tr>
<tr><td>Sanal Ağ</td><td>$($report.VNetSayisi)</td></tr>
<tr><td>Key Vault</td><td>$($report.KeyVaultSayisi)</td></tr>
<tr><td>Aktif Uyarı</td><td class='warn'>$($report.AktifAlert)</td></tr>
</table></body></html>
"@
 
$htmlReport | Out-File "azure_repor_test).html" -Encoding UTF8
Write-Host "HTML raporu olusturuldu." -ForegroundColor Green
 
Continue Reading PowerShell ile Otomatik Kaynak Raporu Üretimi

PowerShell ile Güvenlik Açığı Tarama: Azure Defender Entegrasyonu

Microsoft Defender for Cloud, Azure kaynaklarınızdaki güvenlik açıklarını tespit eder. PowerShell ile güvenlik önerilerini programatik olarak alabilir ve otomatik düzeltme eylemleri başlatabilirsiniz.

Güvenlik Önerilerini Almak

PowerShell

Connect-AzAccount
$recommendations = Get-AzSecurityTask
Write-Host "Toplam güvenlik görevi: $($recommendations.Count)"
 
$highSeverity = $recommendations | Where-Object { $_.RecommendationSeverity -eq "High" }
Write-Host "Yüksek öncelikli: $($highSeverity.Count)" -ForegroundColor Red
 
$highSeverity | Select-Object ResourceId, RecommendationName, RecommendationSeverity | Format-Table -AutoSize

Güvenlik Puanını (Secure Score) Almak

PowerShell

$secureScore = Get-AzSecuritySecureScore
foreach ($score in $secureScore) {
    $pct = [math]::Round(($score.Currentscore / $score.Maxscore) * 100, 1)
    Write-Host "Guvenlik Puanı: $($score.Currentscore)/$($score.Maxscore) (%$pct)"
}
 
$controls = Get-AzSecuritySecureScoreControl
$controls | Sort-Object PercentageScore | Select-Object -First 10 DisplayName, PercentageScore | Format-Table
 

Continue Reading PowerShell ile Güvenlik Açığı Tarama: Azure Defender Entegrasyonu

PowerShell ile Azure Monitor Workbook Oluşturmak

Azure Monitor Workbook’ları, operasyonel verilerinizi görsel olarak sunmanın güçlü bir yoludur. PowerShell ile workbook şablonlarını programatik olarak oluşturabilir ve dağıtabilirsiniz.

Workbook Şablonu Hazırlamak

PowerShell

$workbookTemplate = @{
    version = "Notebook/1.0"
    items = @(
        @{
            type = 1  # Text
            content = @{ json = "## Sanal Makine Performans Raporu\n\nBu workbook tüm VM'lerin CPU ve bellek kullanımını gösterir." }
        }
        @{
            type = 3  # Query
            content = @{
                query = "Perf | where ObjectName == 'Processor' | where CounterName == '% Processor Time' | summarize avg(CounterValue) by Computer, bin(TimeGenerated, 5m)"
                queryType = 0
                resourceType = "microsoft.operationalinsights/workspaces"
            }
        }
    )
} | ConvertTo-Json -Depth 10
 

Workbook Oluşturmak

PowerShell

$rg           = "newrg-"
$workbookName = [guid]::NewGuid().ToString()
$workbookId   = "/subscriptions/bd75202b-2796-442c-afd3-db13313e201d/resourceGroups/$rg/providers/microsoft.insights/workbooks/$workbookName"
 
$params = @{
    Name              = $workbookName
    ResourceGroupName = $rg
    Location          = "uksouth"
    DisplayName       = "VM Performans Raporu"
    SerializedData    = $workbookTemplate
    Category          = "workbook"
    SourceId          = "/subscriptions/bd75202b-2796-442c-afd3-db13313e201d/resourceGroups/$rg/providers/Microsoft.OperationalInsights/workspaces/ml016456056966"
}
 
New-AzApplicationInsightsWorkbook @params
Write-Host "Workbook olusturuldu." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Monitor Workbook Oluşturmak

PowerShell ile Azure DNS Zone ve Kayıt Yönetimi

Kurumsal DNS yönetimi onlarca veya yüzlerce kayıt içerebilir. PowerShell ile DNS kayıtlarını toplu oluşturabilir ve mevcut yapılandırmayı yedekleyebilirsiniz.

DNS Zone ve Kayıt Oluşturmak

PowerShell
New-AzprivateDnsZone -ResourceGroupName "newrg-" -Name "bakionur.com"
 
New-AzprivateDnsRecordSet -ResourceGroupName "newrg-" -ZoneName "bakionur.com" `
    -Name "www" -RecordType A -Ttl 3600 `
    -privatednsrecord (New-AzPrivateDnsRecordConfig -IPv4Address "90.90.90.90")
 
New-AzprivateDnsRecordSet -ResourceGroupName "newrg-" -ZoneName "bakionur.com" `
    -Name "api" -RecordType CNAME -Ttl 3600 `
    -privatednsrecord (New-AzPrivateDnsRecordConfig -Cname "onurtestapp.azurewebsites.net")
Write-Host "DNS kayıtları olusturuldu." -ForegroundColor Green
 

Tüm DNS Kayıtlarını Yedeklemek

PowerShell
$records = Get-AzprivateDnsRecordSet -ResourceGroupName "newrg-" -ZoneName "bakionur.com"
$records | Select-Object Name, RecordType, Ttl,
    @{N="Value"; E={ ($_.Records | ForEach-Object { $_.ToString() }) -join "," }} |
    Export-Csv "dns_backup_$(Get-Date -Format 'yyyyMMdd').csv" -NoTypeInformation
Write-Host "DNS yedegi alındı." -ForegroundColor Cyan
 

Continue Reading PowerShell ile Azure DNS Zone ve Kayıt Yönetimi

PowerShell ile Azure Kubernetes Service (AKS) Yönetimi

AKS kümelerinizi PowerShell üzerinden yönetmek, node ölçekleme ve pod izleme gibi işlemleri otomatize etmenizi sağlar.

AKS Cluster Oluşturmak

PowerShell
New-AzAksCluster `
    -ResourceGroupName "NewRG-" `
    -Name "myAKSClusterOnur1" `
    -Location "uksouth" `
    -NodeCount 3 `
    -NodeVmSize "Standard_D2s_v3" `
    -KubernetesVersion "1.29.0" `
    -NetworkPlugin "azure" `
    -EnableManagedIdentity
Write-Host "AKS cluster olusturuldu." -ForegroundColor Green
 

Kubectl Credentials Almak

PowerShell
Import-AzAksCredential -ResourceGroupName "NewRG-" -Name "myAKSClusterOnur1" -Force
kubectl get nodes
kubectl get pods --all-namespaces
 

Node Pool Ölçeklendirme

PowerShell
$cluster  = Get-AzAksCluster -ResourceGroupName "NewRG-" -Name "myAKSClusterOnur1"
$nodePool = $cluster.AgentPoolProfiles[0]
$nodePool.Count = 5
Set-AzAksCluster -ResourceGroupName "NewRG-" -Name "myAKSClusterOnur1" -NodePoolProfile @($nodePool)
Write-Host "Node count guncellendi: 5" -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Kubernetes Service (AKS) Yönetimi

PowerShell ile Azure Cognitive Services Metin Analizi

Azure Text Analytics (Azure AI Language), metinlerdeki duygu durumunu, anahtar kelimeleri ve dili otomatik olarak analiz edebilir. PowerShell ile bu servisi entegre ederek veri işleme süreçlerinizi akıllı hale getirebilirsiniz.

Duygu Analizi Yapmak

PowerShell

$endpoint = "https://my-language.cognitiveservices.azure.com/"
$apiKey   = (Get-AzKeyVaultSecret -VaultName "myVault" -Name "language-key" -AsPlainText)
$headers  = @{ "Ocp-Apim-Subscription-Key" = $apiKey; "Content-Type" = "application/json" }
 
$body = @{
    documents = @(
        @{ id = "1"; language = "tr"; text = "PowerShell harika bir platform!" }
        @{ id = "2"; language = "tr"; text = "Azure guzel bir platform" }
    )
} | ConvertTo-Json -Depth 3
 
$url      = "$endpoint/text/analytics/v3.1/sentiment"
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method Post -Body $body
$response.documents | ForEach-Object {
    Write-Host "Belge $($_.id): $($_.sentiment) (Pozitif: $([math]::Round($_.confidenceScores.positive*100,1))%)"
}
 

Anahtar Kelime Çıkarımı

PowerShell

$kpUrl = "$endpoint/text/analytics/v3.1/keyPhrases"
$body2 = @{
    documents = @(
        @{ id = "1"; language = "tr"; text = "PowerShell ile Azure yönetimi çok daha verimli hale geliyor. Otomasyon scriptleri operasyonel maliyetleri düşürüyor." }
    )
} | ConvertTo-Json -Depth 3
 
$kpResult = Invoke-RestMethod -Uri $kpUrl -Headers $headers -Method Post -Body $body2
Write-Host "Anahtar kelimeler:"
$kpResult.documents[0].keyPhrases | ForEach-Object { Write-Host "  - $_" }
 

Dil Tespiti

PowerShell
 
$langUrl = "$endpoint/text/analytics/v3.1/languages"
$texts   = @("Hello, how are you?", "Bonjour le monde", "Merhaba dünya", "Hola mundo")
$docs    = $texts | ForEach-Object -Begin { $i=0 } { @{ id = "$i"; text = $_ }; $i++ }
$body3   = @{ documents = $docs } | ConvertTo-Json -Depth 3
 
$langResult = Invoke-RestMethod -Uri $langUrl -Headers $headers -Method Post -Body $body3
$langResult.documents | ForEach-Object {
    Write-Host "Belge $($_.id): $($_.detectedLanguage.name) ($($_.detectedLanguage.iso6391Name))"
}
 

Continue Reading PowerShell ile Azure Cognitive Services Metin Analizi

PowerShell ile Azure VM Image Şablonlarını Listelemek

Düzenli olarak güncel VM imajları kullanmak, güvenlik yamalarının tüm yeni VM’lere otomatik uygulanmasını sağlar. PowerShell ile market imajlarının yeni versiyonlarını izleyebilir ve şablon güncellemelerini tetikleyebilirsiniz.

Marketplace İmajlarını Bulmak

PowerShell

Connect-AzAccount
$location = "uksouth"
 
$publishers = @("MicrosoftWindowsServer","Canonical","RedHat")
foreach ($pub in $publishers) {
    $offers = Get-AzVMImageOffer -Location $location -PublisherName $pub
    foreach ($offer in $offers | Select-Object -First 1) {
        $skus = Get-AzVMImageSku -Location $location -PublisherName $pub -Offer $offer.Offer
        foreach ($sku in $skus | Select-Object -First 1) {
            $latest = Get-AzVMImage -Location $location -PublisherName $pub `
                -Offer $offer.Offer -Skus $sku.Skus | Sort-Object Version -Descending | Select-Object -First 1
            Write-Host "$pub/$($offer.Offer)/$($sku.Skus): $($latest.Version)"
        }
    }
}
 

Continue Reading PowerShell ile Azure VM Image Şablonlarını Listelemek

Proud to be a judge for the 2026 Imagine Cup

Proud to be a judge for the 2026 Imagine Cup, where student startups bring forward the products they’re already building and push them even further.
What stands out every year is the clarity, purpose, and resilience these teams demonstrate. They’re not just competing, they’re refining, iterating, and shaping solutions that can matter in the world.

It’s a privilege to play a small part in their journey and to witness the next generation of builders in action.
Looking forward to what they create!

And if you know a student who should be participating, make sure they register today, https://lnkd.in/eFd65WYp

Continue Reading Proud to be a judge for the 2026 Imagine Cup

PowerShell ile Azure Service Health Olaylarını İzlemek

Azure Service Health, Azure servis kesintilerini ve bakım pencerelerini takip etmenizi sağlar. PowerShell ile bu olayları programatik olarak izleyebilir ve etkilenen kaynakları hızla tespit edebilirsiniz.

Aktif Sağlık Olaylarını Almak

PowerShell
Search-AzGraph -Query "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime)) | where eventType == 'HealthAdvisory' and impactMitigationTime > now()"
Continue Reading PowerShell ile Azure Service Health Olaylarını İzlemek

PowerShell ile Azure Cost Budget ve Harcama Limitleri Yönetimi

Azure bütçeleri, harcamalarınızı belirli eşiklerde uyarı ile takip etmenizi sağlar. PowerShell ile bütçe oluşturabilir, uyarı eşikleri belirleyebilir ve aşım durumunda otomatik aksiyonlar tetikleyebilirsiniz.

Abonelik Düzeyinde Bütçe Oluşturmak

PowerShell

$subscriptionId = (Get-AzContext).Subscription.Id
$token   = (Get-AzAccessToken).Token
$token = ConvertFrom-SecureString -SecureString $Token -AsPlainText
$headers = @{ Authorization = "Bearer $token"; "Content-Type" = "application/json" }
 
$startDate = (Get-Date -Day 1).ToString("yyyy-MM-dd")
$endDate   = (Get-Date -Day 1).AddYears(1).ToString("yyyy-MM-dd")
 
$budget = @{
    properties = @{
        category     = "Cost"
        amount       = 50
        timeGrain    = "Monthly"
        timePeriod   = @{ startDate = $startDate; endDate = $endDate }
        notifications = @{
            "Alert80Pct" = @{
                enabled       = $true
                operator      = "GreaterThan"
                threshold     = 80
                contactEmails = @("finops@towershell.com","platform-team@towershell.com")
                thresholdType = "Actual"
            }
            "Alert100Pct" = @{
                enabled       = $true
                operator      = "GreaterThan"
                threshold     = 100
                contactEmails = @("cto@towershell.com","finops@towershell.com")
                thresholdType = "Actual"
            }
        }
    }
} | ConvertTo-Json -Depth 10
 
$budgetUrl = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Consumption/budgets/MonthlyBudget?api-version=2023-05-01"
Invoke-RestMethod -Uri $budgetUrl -Method Put -Headers $headers -Body $budget
Write-Host "Butce olusturuldu: 50 USD/ay" -ForegroundColor Green
 

Resource Group Bazında Bütçeler

PowerShell

$resourceGroups =  Get-AzResourceGroup -Name aks-rg | Where { $_.Tags["Environment"] -eq "Restricted" } -ErrorAction SilentlyContinue
 
foreach ($rg in $resourceGroups) {
    $rgBudget = @{
        properties = @{
            category  = "Cost"; amount = 500; timeGrain = "Monthly"
            timePeriod = @{ startDate = $startDate; endDate = $endDate }
            filter = @{ dimensions = @{ name = "ResourceGroupName"; operator = "In"; values = @($rg.ResourceGroupName) } }
            notifications = @{
                "RGAlert90" = @{ enabled = $true; operator = "GreaterThan"; threshold = 90
                    contactEmails = @("team@towershell.com"); thresholdType = "Actual" }
            }
        }
    } | ConvertTo-Json -Depth 10
    
    $rgBudgetUrl = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Consumption/budgets/$($rg.ResourceGroupName)-Budget?api-version=2023-05-01"
    Invoke-RestMethod -Uri $rgBudgetUrl -Method Put -Headers $headers -Body $rgBudget
    Write-Host "RG butcesi: $($rg.ResourceGroupName) - 30 USD" -ForegroundColor Cyan
}
 

Continue Reading PowerShell ile Azure Cost Budget ve Harcama Limitleri Yönetimi

PowerShell ile Azure Load Balancer Oluşturmak

Azure Load Balancer, yüksek kullanılabilirlik gerektiren uygulamalar için trafiği birden fazla VM arasında dağıtır. PowerShell ile yapılandırmasını programatik olarak yönetebilirsiniz.

Public Load Balancer Oluşturmak

PowerShell

$rg = "newrg-"; $location = "eastus"
 
$publicIP    = New-AzPublicIpAddress -ResourceGroupName $rg -Name "lb-ip" -Location $location -Sku Standard -AllocationMethod Static
$frontendIP  = New-AzLoadBalancerFrontendIpConfig -Name "FrontendIP" -PublicIpAddress $publicIP
$backendPool = New-AzLoadBalancerBackendAddressPoolConfig -Name "BackendPool"
$probe       = New-AzLoadBalancerProbeConfig -Name "HealthProbe" -Protocol Http -Port 80 -RequestPath "/" -IntervalInSeconds 15 -ProbeCount 3
$lbRule      = New-AzLoadBalancerRuleConfig -Name "HTTPRule" -Protocol Tcp `
    -FrontendPort 80 -BackendPort 80 `
    -FrontendIpConfiguration $frontendIP -BackendAddressPool $backendPool -Probe $probe
 
New-AzLoadBalancer -ResourceGroupName $rg -Name "myLB" -Location $location -Sku Standard `
    -FrontendIpConfiguration $frontendIP -BackendAddressPool $backendPool -Probe $probe -LoadBalancingRule $lbRule
Write-Host "Load Balancer olusturuldu." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Load Balancer Oluşturmak

PowerShell ile Azure Role Assignment Audit ve Temizlik

Zamanla Azure ortamlarında gereksiz rol atamaları birikir. PowerShell ile tüm rol atamalarını denetleyebilir, yetim atamaları (silinmiş kullanıcılar) bulabilir ve güvenlik açıklarını kapatabilirsiniz.

Tüm Rol Atamalarını Analiz Etmek

PowerShell

#Connect-AzAccount
$allAssignments = Get-AzRoleAssignment
 
Write-Host "Toplam rol ataması: $($allAssignments.Count)"
 
# Tip bazında dağılım
$allAssignments | Group-Object SignInType | ForEach-Object {
    Write-Host "  $($_.Name ?? 'Bilinmiyor'): $($_.Count)"
}
 
# Owner rolüne sahip olanlar
$owners = $allAssignments | Where-Object { $_.RoleDefinitionName -eq "Owner" }
Write-Host "Owner rol a

Yetim Atamaları Bulmak

PowerShell

$orphanedAssignments = $allAssignments | Where-Object {
    $_.ObjectType -eq "Unknown"  # Silinmiş kullanıcı/servis principal
}
 
Write-Host "Yetim atama sayısı: $($orphanedAssignments.Count)" -ForegroundColor Red
 
$orphanedAssignments | Select-Object RoleDefinitionName, ObjectId, Scope | Format-Table
 

Yetim Atamaları Kaldırmak

PowerShell
$orphanedAssignments | ForEach-Object {
    Remove-AzRoleAssignment `
        -ObjectId $_.ObjectId `
        -RoleDefinitionName $_.RoleDefinitionName `
        -Scope $_.Scope `
        -ErrorAction SilentlyContinue
    Write-Host "Kaldırıldı: $($_.RoleDefinitionName) - $($_.ObjectId)"
}
 
Write-Host "Yetim atamalar temizlendi." -ForegroundColor Green
 

Bende yok ama sizde olabilir; yine de ekleyeyim bunu da..

Continue Reading PowerShell ile Azure Role Assignment Audit ve Temizlik

PowerShell ile Azure Resource Lock Yönetimi

Azure Resource Lock’lar, kritik kaynakların yanlışlıkla silinmesini veya değiştirilmesini engeller. PowerShell ile kilitleri programatik olarak yönetebilirsiniz.

Silme Kilidi Oluşturmak

PowerShell
New-AzResourceLock -LockName "ProdStorageLock" -LockLevel CanNotDelete `
    -ResourceName "lb-ip" `
    -ResourceType "Microsoft.Network/publicIPAddresses" `
    -ResourceGroupName "NewRG-" -Force
Write-Host "Silme kilidi uygulandı." -ForegroundColor Green
 
New-AzResourceLock -LockName "ProdRGReadOnly" -LockLevel ReadOnly `
    -ResourceGroupName "newRG-" -Force
Write-Host "Resource group ReadOnly kilitlendi." -ForegroundColor Green
 

test edelim…

Kilitleri Kaldırmak

PowerShell
function Remove-RGLocks {
    param([string]$ResourceGroup)
    $locks = Get-AzResourceLock -ResourceGroupName "newrg-"
    foreach ($lock in $locks) {
        Remove-AzResourceLock -LockId $lock.LockId -Force
        Write-Host "Kaldırıldı: $($lock.Name)"
    }
    Write-Host "Tüm kilitler kaldırıldı." -ForegroundColor Yellow
}
 
Remove-RGLocks -ResourceGroup "newrg-"

Yine test edelim

Continue Reading PowerShell ile Azure Resource Lock Yönetimi

PowerShell ile Azure Managed Identity ile Güvenli Kimlik Doğrulama

Scriptlerde kullanıcı adı/şifre saklamak büyük güvenlik açığıdır. Azure Managed Identity, Azure servislerinin kimlik bilgisi gerektirmeden iletişim kurmasını sağlar.

Managed Identity Etkinleştirmek

PowerShell
$vm = Get-AzVM -ResourceGroupName "jump" -Name "jmp01"
Update-AzVM -ResourceGroupName "vpntest" -VM $vm -IdentityType SystemAssigned
Write-Host "System-Assigned Managed Identity etkinlestirildi."
 

RBAC Rolü Atamak

PowerShell
$vm = Get-AzVM -ResourceGroupName "jump" -Name "jmp01"
$principalId = $vm.Identity.PrincipalId
 
New-AzRoleAssignment `
    -ObjectId $principalId `
    -RoleDefinitionName "Key Vault Secrets User" `
    -Scope "/subscriptions/bd75202b-2796-442c-afd3-db13313e201d/resourceGroups/AI/providers/Microsoft.KeyVault/vaults/ml012437143227"
Write-Host "Rol atandı." -ForegroundColor Green

Managed Identity ile Giriş Yapmak

PowerShell
Connect-AzAccount -Identity
 
$secret = Get-AzKeyVaultSecret -VaultName "ml012437143227" -Name "supersecret999" -AsPlainText

Continue Reading PowerShell ile Azure Managed Identity ile Güvenli Kimlik Doğrulama

PowerShell ile Azure Automation Runbook Oluşturmak ve Yayınlamak

Azure Automation Runbook’ları, tekrarlayan yönetim görevlerini bulutta çalıştırmanıza olanak tanır. PowerShell ile runbook oluşturabilir, yayınlayabilir ve zamanlanmış görevler kurabilirsiniz. ManagedID ve hedef kaynaktaki yetki durumuna dikkat!

Automation Account Oluşturmak

PowerShell
$resourceGroup    = "vpntest "
$automationAccount = " automationacc00009"
$location          = "uksouth"
 
New-AzAutomationAccount `
    -ResourceGroupName $resourceGroup `
    -Name $automationAccount `
    -Location $location `
    -Plan "Basic"
Write-Host "Automation Account olusturuldu." -ForegroundColor Green
 

Runbook Script Dosyası Oluşturmak

PowerShell
$scriptContent = @'
param([string]$ResourceGroup = "vpntest")
Connect-AzAccount -Identity
$vms = Get-AzVM -ResourceGroupName $ResourceGroup
foreach ($vm in $vms) {
    $status = (Get-AzVM -Name $vm.Name -Status).Statuses | Where-Object { $_.Code -like "PowerState*" }
    if ($status.DisplayStatus -eq "VM running") {
        Stop-AzVM -Name $vm.Name -ResourceGroupName $ResourceGroup -Force | Out-Null
        Write-Output "Durduruldu: $($vm.Name)"
    }
}
'@
$scriptPath = "Stop-UnusedVMs.ps1"
$scriptContent | Out-File $scriptPath -Encoding UTF8
 

Runbook’u İçe Aktarmak ve Yayınlamak

PowerShell
Import-AzAutomationRunbook `
    -ResourceGroupName vpntest `
    -AutomationAccountName "automationacc00009"`
    -Name "Stop-UnusedVMs" `
    -Type PowerShell `
    -Path "Stop-UnusedVMs.ps1" | out-null
 
Publish-AzAutomationRunbook `
    -ResourceGroupName vpntest `
    -AutomationAccountName "automationacc00009"` `
    -Name "Stop-UnusedVMs" | out-null
Write-Host "Runbook yayınlandı." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Automation Runbook Oluşturmak ve Yayınlamak

PowerShell ile Azure Subscription Etiket (Tag) Politikası Uygulama

Kurumsal Azure ortamlarında kaynak etiketlemesi, maliyet takibi ve yönetişim için kritik öneme sahiptir. PowerShell ile tüm abonelik genelinde eksik etiketleri tespit edip toplu olarak uygulayabilirsiniz.

Etiketsiz Kaynakları Bulmak

PowerShell

#Connect-AzAccount
$untagged = Get-AzResource -resourcegroupname "newrg-" | Where-Object { $_.Tags -eq $null -or $_.Tags.Count -eq 0 }
Write-Host "Etiketsiz kaynak sayısı: $($untagged.Count)" -ForegroundColor Yellow
$untagged | Select-Object Name, ResourceType, ResourceGroupName | Format-Table -AutoSize
 

Toplu Etiket Eklemek

PowerShell

$mandatoryTags = @{
    "Environment"  = "Non-Prod"
    "CostCenter"   = "MVP01"
    "Owner"        = "admin@bakionur.com"
    "ManagedBy"    = "PowerShell"
}
 
foreach ($resource in $untagged) {
    $existingTags = $resource.Tags ?? @{}
    $mergedTags   = $existingTags + $mandatoryTags
    Update-AzTag -ResourceId $resource.ResourceId -Tag $mergedTags -Operation Merge | Out-Null
    Write-Host "Etiketlendi: $($resource.Name)" -ForegroundColor Green
}
 

Tag Uyumluluk Raporu

PowerShell

$allResources = Get-AzResource -resourcegroupname "newrg-"
$report = $allResources | ForEach-Object {
    [PSCustomObject]@{
        Kaynak      = $_.Name
        Tip         = $_.ResourceType
        Environment = $_.Tags["Environment"] ?? "EKSIK"
        CostCenter  = $_.Tags["CostCenter"]  ?? "EKSIK"
        Owner       = $_.Tags["Owner"]       ?? "EKSIK"
    }
}
$report | Where-Object { $_.Environment -eq "EKSIK" -or $_.CostCenter -eq "EKSIK" }

Continue Reading PowerShell ile Azure Subscription Etiket (Tag) Politikası Uygulama

PowerShell ile Azure Policy Uyumluluk Raporunu Almak

Azure Policy, kaynaklarınızın kurumsal standartlarla uyumlu olup olmadığını denetler. PowerShell ile politika uyumluluk raporlarını otomatik olarak çekebilir ve ilgili ekiplere dağıtabilirsiniz.

Uyumluluk Özetini Almak

PowerShell

Connect-AzAccount
$summary = Get-AzPolicyStateSummary
Write-Host "Uyumlu: $($summary.Results.ResourceDetails.CompliantCount)"
Write-Host "Uyumsuz: $($summary.Results.ResourceDetails.NonCompliantCount)"
 

Uyumsuz Kaynakları Listelemek

PowerShell

$nonCompliant = Get-AzPolicyState `
    -Filter "ComplianceState eq 'NonCompliant'" `
    -Top 100
 
$nonCompliant | Select-Object @{l=resourcename;e={$($_.resourceid).split(/)[-1]}},PolicyDefinitionName, ComplianceState| Format-Table -AutoSize
 

Continue Reading PowerShell ile Azure Policy Uyumluluk Raporunu Almak

PowerShell ile Azure Trusted Launch VM Güvenlik Profili Almak

Azure Trusted Launch, VM’lerinizi rootkit ve bootkit saldırılarına karşı korumak için Secure Boot ve vTPM gibi özellikler sunar. PowerShell ile bu güvenlik özelliklerini etkinleştirebilirsiniz.

Mevcut VM’lerin Trusted Launch Durumunu Kontrol Etmek

PowerShell

$vms = Get-AzVM -ResourceGroupName vpntest
$report = $vms | ForEach-Object {
    $secProfile = $_.SecurityProfile
    [PSCustomObject]@{
        VMName      = $_.Name
        SecurityType = $secProfile?.SecurityType ?? "Standard"
        SecureBoot  = $secProfile?.UefiSettings?.SecureBootEnabled ?? $false
        vTPM        = $secProfile?.UefiSettings?.VTpmEnabled ?? $false
    }
}
$report | Format-Table -AutoSize
$report | Where-Object { $_.SecurityType -ne "TrustedLaunch" } |
    Export-Csv "non-trusted-vms.csv" -NoTypeInformation
Write-Host "Rapor kaydedildi." -ForegroundColor Cyan
 

Continue Reading PowerShell ile Azure Trusted Launch VM Güvenlik Profili Almak

PowerShell ile AES Dosya Şifreleme ve Şifre Çözme

Hassas verileri şifrelemek kritik bir güvenlik gereksinimidir. PowerShell’in .NET altyapısını kullanarak AES şifreleme ile dosyalarınızı güvenli şekilde koruyabilirsiniz.

Dosya Şifreleme

PowerShell
function Protect-File {
    param([string]$InputFile, [string]$OutputFile, [string]$Password)
    $salt    = New-Object byte[] 32
    [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($salt)
    $derive  = New-Object System.Security.Cryptography.Rfc2898DeriveBytes($Password, $salt, 100000)
    $aes     = [System.Security.Cryptography.Aes]::Create()
    $aes.Key = $derive.GetBytes(32); $aes.IV = $derive.GetBytes(16)
    $inBytes = [System.IO.File]::ReadAllBytes($InputFile)
    $enc     = $aes.CreateEncryptor().TransformFinalBlock($inBytes, 0, $inBytes.Length)
    [System.IO.File]::WriteAllBytes($OutputFile, $salt + $enc)
    Write-Host "Sifrelendi: $OutputFile" -ForegroundColor Green
}
 

Şifre Çözme

PowerShell
function Unprotect-File {
    param([string]$InputFile, [string]$OutputFile, [string]$Password)
    $all    = [System.IO.File]::ReadAllBytes($InputFile)
    $salt   = $all[0..31]; $enc = $all[32..($all.Length-1)]
    $derive = New-Object System.Security.Cryptography.Rfc2898DeriveBytes($Password, $salt, 100000)
    $aes    = [System.Security.Cryptography.Aes]::Create()
    $aes.Key = $derive.GetBytes(32); $aes.IV = $derive.GetBytes(16)
    $dec    = $aes.CreateDecryptor().TransformFinalBlock($enc, 0, $enc.Length)
    [System.IO.File]::WriteAllBytes($OutputFile, $dec)
    Write-Host "Sifre cozuldu: $OutputFile" -ForegroundColor Green
}
 
Protect-File   -InputFile "gizli.txt" -OutputFile "gizli.enc" -Password "G1zl1P@ss!"
Unprotect-File -InputFile "gizli.enc"  -OutputFile "gizli_cozulmus.txt" -Password "G1zl1P@ss!"
 

Continue Reading PowerShell ile AES Dosya Şifreleme ve Şifre Çözme

PowerShell ile Azure Redis Cache Yönetimi

Azure Cache for Redis, uygulamalarınıza yüksek performanslı önbellekleme katmanı ekler. PowerShell ile Redis instance’larını oluşturabilir, izleyebilir ve yapılandırabilirsiniz.

Redis Cache Oluşturmak

PowerShell

$rg        = "newrg-"
$cacheName = "onurtestrediscache"
$location  = "eastus"
 
New-AzRedisCache -ResourceGroupName $rg -Name $cacheName `
    -Location $location -Size C1 -Sku Standard
 
$redis = Get-AzRedisCache -ResourceGroupName $rg -Name $cacheName
Write-Host "Redis Endpoint: $($redis.HostName):$($redis.SslPort)"
 

Connection string listelemek

PowerShell

$keys = Get-AzRedisCacheKey -ResourceGroupName $rg -Name $cacheName
Write-Host "Primary Key: $($keys.PrimaryKey.Substring(0,20))..."
 
$connStr = "$cacheName.redis.cache.windows.net:6380,password=$($keys.PrimaryKey),ssl=True,abortConnect=False"
Write-Host "Connection string ready."
 

Continue Reading PowerShell ile Azure Redis Cache Yönetimi

PowerShell ile Azure Disk Encryption Durumu Denetimi

Azure Disk Encryption, VM disk verilerini şifreleyerek veri güvenliğini sağlar. PowerShell ile tüm VM’lerin disk şifreleme durumunu toplu olarak kontrol edebilirsiniz.

Şifrelenmemiş VM’leri Tespit Etmek

PowerShell

#connect-AzAccount
$allVMs = Get-AzVM
$report = @()
 
foreach ($vm in $allVMs) {
    $encStatus = Get-AzVmDiskEncryptionStatus -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name
    $report += [PSCustomObject]@{
        VMName          = $vm.Name
        ResourceGroup   = $vm.ResourceGroupName
        OSDisk          = $encStatus.OsVolumeEncryptionSettings.Enabled ?? $false
        DataDisks       = $encStatus.DataVolumesEncryptionStatus -ne "NotEncrypted"
        EncryptionExtension = $encStatus.ProgressMessage
    }
}
 
$unencrypted = $report | Where-Object { -not $_.OSDisk }
Write-Host "Şifrelenmemiş VM sayısı: $($unencrypted.Count)" -ForegroundColor Red
$unencrypted | Format-Table
$report | Export-Csv "disk_encryption_audit.csv" -NoTypeInformation
 

Continue Reading PowerShell ile Azure Disk Encryption Durumu Denetimi

PowerShell ile Azure AI Foundry’de Model Deployment Durumunu Kontrol Etmek

Azure AI Foundry üzerinde model deployment işlemleri bazen uzun sürebilir. PowerShell ile bu durumu programatik olarak izlemek, hem zamandan tasarruf ettirir hem de hataları erkenden fark etmenizi sağlar.

Azure Portal üzerinden manuel kontrol yapmak yerine PowerShell ile otomatik bir döngü kurarak deployment durumunu düzenli aralıklarla sorgulayabilirsiniz. Bu yaklaşım özellikle CI/CD pipeline’larında deployment onayı beklerken kritik önem taşır.

Az.CognitiveServices modülünü yükledikten sonra aşağıdaki komutla deployment durumunu sorgulayabilirsiniz:

PowerShell
Install-Module -Name Az.CognitiveServices -Force
#Connect-AzAccount
 
$resourceGroup = "AI"
$accountName   = "heyhey"
$deploymentName = "gpt-4.1"
 
$deployment = Get-AzCognitiveServicesAccountDeployment `
    -ResourceGroupName $resourceGroup `
    -AccountName $accountName `
    -Name $deploymentName
 
Write-Host "Deployment Durumu: $($deployment.Properties.ProvisioningState)"

Hatta, deployment tamamlanana kadar belirli aralıklarla kontrol eden bir döngü kullanabilirsiniz:

PowerShell
do {
    $deployment = Get-AzCognitiveServicesAccountDeployment `
        -ResourceGroupName $resourceGroup `
        -AccountName $accountName `
        -Name $deploymentName
 
    $status = $deployment.Properties.ProvisioningState
    Write-Host "$(Get-Date -Format 'HH:mm:ss') - Durum: $status"
    Start-Sleep -Seconds 30
} while ($status -ne "Succeeded" -and $status -ne "Failed")
 
if ($status -eq "Succeeded") {
    Write-Host "Deployment basarıyla tamamlandı!" -ForegroundColor Green
} else {
    Write-Host "Deployment basarısız oldu!" -ForegroundColor Red
}
 

Bu scripti Azure DevOps pipeline task’ı olarak çalıştırabilir veya Logic App ile de entegre edebilirsiniz. Deployment başarısız olduğunda farkli aksiyonlar ekleyebilirsiniz.

Continue Reading PowerShell ile Azure AI Foundry’de Model Deployment Durumunu Kontrol Etmek

PowerShell ile Log Analytics Workspace’e Özel Log Göndermek

Azure Log Analytics yalnızca Azure kaynaklarından değil, özel uygulamalarınızdan da log verisi kabul eder. PowerShell ile HTTP Data Collector API’sini kullanarak kendi verilerinizi gönderebilirsiniz.

HMAC İmzalama Fonksiyonu

PowerShell
function Build-LASignature {
    param($workspaceId, $sharedKey, $date, $contentLength, $method, $contentType, $resource)
    $xHeaders = "x-ms-date:" + $date
    $stringToHash = "$method`n$contentLength`n$contentType`n$xHeaders`n$resource"
    $bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
    $keyBytes    = [Convert]::FromBase64String($sharedKey)
    $sha256      = New-Object System.Security.Cryptography.HMACSHA256
    $sha256.Key  = $keyBytes
    $encodedHash = [Convert]::ToBase64String($sha256.ComputeHash($bytesToHash))
    return "SharedKey " + $workspaceId + ":" + $encodedHash
}
 

Log Göndermek

PowerShell
function Send-LAData {
    param($workspaceId, $sharedKey, $body, $logType)
    $date     = [DateTime]::UtcNow.ToString("r")
    $length   = ([Text.Encoding]::UTF8.GetBytes($body)).Length
    $sig      = Build-LASignature $workspaceId $sharedKey $date $length "POST" "application/json" "/api/logs"
    $uri      = "https://$workspaceId.ods.opinsights.azure.com/api/logs?api-version=2016-04-01"
    $headers  = @{ Authorization = $sig; "Log-Type" = $logType; "x-ms-date" = $date }
    Invoke-WebRequest -Uri $uri -Method Post -ContentType "application/json" -Headers $headers -Body $body
}
 
$data = @(@{ Sunucu = "WEB01"; Durum = "OK"; Gecikme = 120 }) | ConvertTo-Json
Send-LAData -workspaceId "$workspaceid" -sharedKey "$primarykey" -body $data -logType "CustomAppLogs_CL" | out-null
Write-Host "Log gönderildi." -ForegroundColor Green
 

Continue Reading PowerShell ile Log Analytics Workspace’e Özel Log Göndermek

PowerShell ile Uzak Sunucularda Sistem Envanteri Toplamak

Birden fazla Windows sunucusunun sistem bilgilerini toplamak ve merkezi bir rapora dönüştürmek, sistem yöneticileri için sık gereken bir işlemdir. PowerShell ile bu süreci tamamen otomatize edebilirsiniz.

Sistem Bilgileri Toplama Fonksiyonu

PowerShell

function Get-SystemInventory {
    param([string[]]$ComputerNames)
    $inventory = @()
    foreach ($computer in $ComputerNames) {
        try {
            $os   = Get-CimInstance -ComputerName $computer Win32_OperatingSystem
            $cpu  = Get-CimInstance -ComputerName $computer Win32_Processor | Select-Object -First 1
            $disk = Get-CimInstance -ComputerName $computer Win32_LogicalDisk -Filter "DriveType=3"
            $inventory += [PSCustomObject]@{
                Sunucu     = $computer
                OS         = $os.Caption
                RAM_GB     = [math]::Round($os.TotalVisibleMemorySize / 1MB, 2)
                CPU        = $cpu.Name
                DiskBos_GB = [math]::Round(($disk | Measure-Object FreeSpace -Sum).Sum / 1GB, 2)
            }
        } catch { Write-Warning "$computer erisir: $($_.Exception.Message)" }
    }
    return $inventory
}

$rapor = Get-SystemInventory -ComputerNames @("SERVER01","SERVER02","SERVER03")
$rapor | Format-Table -AutoSize
$rapor | Export-Csv "system_inventory.csv" -NoTypeInformation

Ben localhost ile ilerleyeyim, zira kendi makinem! :)

Continue Reading PowerShell ile Uzak Sunucularda Sistem Envanteri Toplamak

PowerShell ile Azure Blob Storage Lifecycle Politikası Yönetimi

Azure Blob Storage lifecycle politikaları, verilerin otomatik olarak daha ucuz depolama katmanlarına taşınmasını sağlar. PowerShell ile bu politikaları programatik olarak oluşturabilir ve yönetebilirsiniz.

Lifecycle Politikası Oluşturmak

PowerShell

$rg          = "newrg-"
$storageName = "newrgstracc0001"
 
$policy = @{
    rules = @(
        @{
            name    = "MoveToArchive"
            enabled = $true
            type    = "Lifecycle"
            definition = @{
                actions = @{
                    baseBlob = @{
                        tierToCool    = @{ daysAfterModificationGreaterThan = 30  }
                        tierToArchive = @{ daysAfterModificationGreaterThan = 180  }
                        delete        = @{ daysAfterModificationGreaterThan = 365 }
                    }
                }
                filters = @{ blobTypes = @("blockBlob"); prefixMatch = @("logs/","backups/","/tests") }
            }
        }
    )
} | ConvertTo-Json -Depth 10
 
Update-AzStorageBlobServiceProperty -ResourceGroupName $rg -StorageAccountName $storageName
Write-Host "Lifecycle politikası uygulandı." -ForegroundColor Green
 

Mevcut Politikayı Okumak

PowerShell

$ctx = (Get-AzStorageAccount -ResourceGroupName $rg -Name $storageName).Context
$service = Get-AzStorageBlobServiceProperty -ResourceGroupName $rg -StorageAccountName $storageName
Write-Host "Delete retention: $($service.DeleteRetentionPolicy.Days) gun"
$service

Continue Reading PowerShell ile Azure Blob Storage Lifecycle Politikası Yönetimi

PowerShell ile Windows Scheduled Task Oluşturmak

Windows Scheduled Tasks, scriptlerinizi belirli aralıklarla otomatik çalıştırmanın temel mekanizmasıdır. PowerShell ile bu görevleri programatik olarak oluşturabilir ve yönetebilirsiniz.

Günlük Görev Oluşturmak

PowerShell
$action   = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument "-NonInteractive -File C:\Scripts\cleanup.ps1"
$trigger  = New-ScheduledTaskTrigger -Daily -At "02:00AM"
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 1) -RestartCount 3
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest
 
Register-ScheduledTask -TaskName "DailyCleanup" -TaskPath "\MyScripts\" `
    -Action $action -Trigger $trigger -Settings $settings -Principal $principal
Write-Host "Gorev olusturuldu: DailyCleanup" -ForegroundColor Green
 

Continue Reading PowerShell ile Windows Scheduled Task Oluşturmak

PowerShell ile Azure Disk Yönetimi ve Snapshot Alma

Azure Managed Disk snapshot’ları, VM’lerinizin belirli bir andaki disk görüntülerini saklar. PowerShell ile snapshot alma, yönetme ve diskten VM oluşturma işlemlerini otomatize edebilirsiniz.

VM Disklerini Listelemek

PowerShell

$rg   = "vpntest"
$vm   = Get-AzVM -ResourceGroupName $rg -Name "vpntest"
 
Write-Host "OS Disk: $($vm.StorageProfile.OsDisk.Name)"
Write-Host "Veri diskleri:"
$vm.StorageProfile.DataDisks | ForEach-Object {
    $disk = Get-AzDisk -ResourceGroupName $rg -DiskName $_.Name
    Write-Host "  $($_.Name): $($disk.DiskSizeGB) GB, $($disk.Sku.Name)"
}
 

Snapshot Almak

PowerShell

$diskName = $vm.StorageProfile.OsDisk.Name
$disk     = Get-AzDisk -ResourceGroupName $rg -DiskName $diskName
 
$snapshotConfig = New-AzSnapshotConfig `
    -SourceUri $disk.Id `
    -Location $disk.Location `
    -CreateOption Copy `
    -AccountType Standard_LRS
 
$snapshotName = "$diskName-snap-09_08_2025"
New-AzSnapshot -ResourceGroupName $rg -SnapshotName $snapshotName -Snapshot $snapshotConfig | Out-Null
Write-Host "Snapshot alındı: $snapshotName" -ForegroundColor Green

Eski Snapshot’ları Temizlemek

PowerShell

$retentionDays = 30
$cutoff        = (Get-Date).AddDays(-$retentionDays)
 
$oldSnapshots = Get-AzSnapshot -ResourceGroupName vpntest |
    Where-Object { $_.TimeCreated -lt $cutoff }
 
Write-Host "Silinecek snapshot sayısı: $($oldSnapshots.Count)"
foreach ($snap in $oldSnapshots) {
    Remove-AzSnapshot -ResourceGroupName vpntest -SnapshotName $snap.Name -Force
    Write-Host "Silindi: $($snap.Name)"
}
 

Continue Reading PowerShell ile Azure Disk Yönetimi ve Snapshot Alma

PowerShell ile Azure Network Performance Monitor

Ağ performansını sürekli izlemek, kullanıcı deneyimini doğrudan etkileyen gecikme ve kayıp sorunlarını proaktif olarak tespit etmenizi sağlar. PowerShell ile NPM verilerini analiz edebilirsiniz.

Ağ Bağlantısını Test Etmek

PowerShell

function Test-NetworkPath {
    param(
        [string[]]$SourceIPs,
        [string[]]$DestinationHosts,
        [int]$Port = 443
    )
    
    $results = @()
    foreach ($src in $SourceIPs) {
        foreach ($dest in $DestinationHosts) {
            $latencies = @()
            1..5 | ForEach-Object {
                $start = Get-Date
                $conn  = Test-NetConnection -ComputerName $dest -Port $Port -WarningAction SilentlyContinue
                $end   = Get-Date
                if ($conn.TcpTestSucceeded) { $latencies += ($end - $start).TotalMilliseconds }
            }
            
            $results += [PSCustomObject]@{
                Kaynak    = $src
                Hedef     = $dest
                Port      = $Port
                Basarili  = ($latencies.Count -gt 0)
                OrtGecikme = if ($latencies.Count -gt 0) { [math]::Round(($latencies | Measure-Object -Average).Average, 2) } else { $null }
                MaxGecikme = if ($latencies.Count -gt 0) { [math]::Round(($latencies | Measure-Object -Maximum).Maximum, 2) } else { $null }
            }
        }
    }
    return $results
}
 
$networkTests = Test-NetworkPath `
    -SourceIPs @("10.0.1.10","10.0.2.10") `
    -DestinationHosts @("portal.azure.com","login.microsoftonline.com","myapp.azurewebsites.net") `
    -Port 443
 
$networkTests | Format-Table -AutoSize
 

Continue Reading PowerShell ile Azure Network Performance Monitor

PowerShell ile Azure Container Registry Temizliği

Azure Container Registry zamanla eski ve kullanılmayan image’larla dolabilir. PowerShell ile eski image manifest’larını otomatik olarak temizleyebilirsiniz.

Registry Bilgilerini Almak

PowerShell
$registryName = "devacrtjoo7ltn6u6uo"
$resourceGroup = "rg-dev"
$acr = Get-AzContainerRegistry -ResourceGroupName $resourceGroup -Name $registryName
Write-Host "Registry URL: $($acr.LoginServer)"
 

Repository Listesini Almak

PowerShell
$repos = az acr repository list --name $registryName | ConvertFrom-Json
Write-Host "Toplam repository: $($repos.Count)"
 

Eski Image’ları Temizlemek

PowerShell
$registryName = "devacrtjoo7ltn6u6uo"
$resourceGroup = "rg-dev"
$acr = Get-AzContainerRegistry -ResourceGroupName $resourceGroup -Name $registryName
Write-Host "Registry URL: $($acr.LoginServer)"


$repos = az acr repository list --name $registryName | ConvertFrom-Json
Write-Host "Toplam repository: $($repos.Count)"



$cutoffDate = (Get-Date).AddDays(-30)
foreach ($repo in $repos) {
    $manifests = az acr repository show-manifests --name $registryName --repository $repo --orderby time_asc | ConvertFrom-Json
    $old = $manifests | Where-Object { ([DateTime]$_.timestamp).ToString("yyyy-MM-ddTHH:mm:ssZ") }
    foreach ($m in $old) {
        az acr repository delete --name $registryName --image "${repo}@$($m.digest)" --yes
        Write-Host "Silindi: $repo digest=$($m.digest)"
    }
}
Write-Host "Temizlik tamamlandı." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Container Registry Temizliği

PowerShell ile Azure Resource Graph Kullanarak Tüm Abonelikleri Taramak

Büyük kurumsal ortamlarda onlarca Azure aboneliği (subscription) bulunabilir, ki genelde de bulunur. Azure Resource Graph, tüm aboneliklerdeki kaynakları tek bir sorguyla taramanıza olanak tanır.

Azure Resource Graph, milyonlarca Azure kaynağını milisaniyeler (tamam tamam saniye olsun) içinde sorgulamanızı sağlayan bir hizmettir. KQL (Kusto Query Language) tabanlı sorgularla tüm aboneliklerinizi tek seferde (tenant seviyesinde) tarayabilirsiniz.

PowerShell
Install-Module -Name Az.ResourceGraph -Force -AllowClobber
Import-Module Az.ResourceGraph
 
$query = "Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| project name, resourceGroup, location, subscriptionId
| order by name asc"
 
$result = Search-AzGraph -Query $query -First 1000
$result | Format-Table -AutoSize

Kullanılmayan Public IP’leri Bulmak

PowerShell

$unusedIPQuery = "Resources
| where type =~ 'Microsoft.Network/publicIPAddresses'
| where isnull(properties.ipConfiguration)
| project name, resourceGroup, location, subscriptionId"
 
$unusedIPs = Search-AzGraph -Query $unusedIPQuery
Write-Host "Kullanılmayan Public IP sayısı: $($unusedIPs.Count)" -ForegroundColor Yellow
$unusedIPs | Export-Csv -Path "unused_ips.csv" -NoTypeInformation

Resource Graph varsayılan olarak 1000 kayıt döndürür. Daha fazlası için -Skip parametresiyle sayfalama yapabilirsiniz.

Continue Reading PowerShell ile Azure Resource Graph Kullanarak Tüm Abonelikleri Taramak

PowerShell ile Azure Virtual Network ve Subnet Yönetimi

Ağ altyapısını kod ile yönetmek (Network as Code), tutarlı ve tekrarlanabilir network yapıları oluşturmanın temelidir. PowerShell ile VNet ve Subnet’leri programatik olarak yönetebilirsiniz.

VNet Oluşturmak

PowerShell
$vnet = New-AzVirtualNetwork `
    -Name "vnet-production" `
    -ResourceGroupName "NewRG-" `
    -Location "uksouth" `
    -AddressPrefix "10.0.0.0/16"
Write-Host "VNet olusturuldu."
 

Subnet Eklemek

PowerShell
$subnets = @(
    @{ Name = "snet-frontend"; Prefix = "10.0.1.0/24" }
    @{ Name = "snet-backend";  Prefix = "10.0.2.0/24" }
    @{ Name = "snet-database"; Prefix = "10.0.3.0/24" }
)
foreach ($subnet in $subnets) {
    Add-AzVirtualNetworkSubnetConfig -Name $subnet.Name -VirtualNetwork $vnet -AddressPrefix $subnet.Prefix | Out-Null
    Write-Host "Subnet eklendi: $($subnet.Name)"
}
$vnet | Set-AzVirtualNetwork | Out-Null
Write-Host "Tum subnetler uygulandı." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Virtual Network ve Subnet Yönetimi

PowerShell ile Azure Policy as Code – Part 1: Policy Export

Azure Policy’yi kod olarak yönetmek, değişikliklerin izlenebilmesini ve geri alınabilmesini sağlar. PowerShell ile policy tanımlarını (definition) JSON dosyalarına aktarabilir, versiyon kontrolüne alabilir ve CI/CD pipeline’ı üzerinden dağıtabilirsiniz.

Tüm Azure Policy Tanımlarını Dışa Aktarmak

PowerShell

$subscriptionId = (Get-AzContext).Subscription.Id -warning
$outputDir = "C:\tmp\PolicyAsCode\definitions"
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
 
$customPolicies = Get-AzPolicyDefinition -Custom
foreach ($policy in $customPolicies) {
    $fileName = "$outputDir\$($policy.Name).json"
    $policy | ConvertTo-Json -Depth 20 | Out-File $fileName -Encoding UTF8
    Write-Host "Dısarı aktarıldı: $($policy.Properties.DisplayName)"
}
Write-Host "Toplam $($customPolicies.Count) politika aktarıldı." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Policy as Code – Part 1: Policy Export

PowerShell ile Azure Private Endpoint Yapılandırması

Azure Private Endpoint, servislere internet yerine özel ağınız üzerinden erişim sağlar. Bu yaklaşım güvenlik açısından kritiktir ve PowerShell ile yapılandırması sistemlidir.

Private Endpoint Oluşturmak

PowerShell

$storageId = (Get-AzStorageAccount -ResourceGroupName "ai" -Name "filesharetest01234").Id

$subnet= (Get-AzVirtualNetwork -Name "vpntest-vnet" -ResourceGroupName "vpntest").Subnets |
             Where-Object { $_.Name -eq "ggg" }
 
$plsConn = New-AzPrivateLinkServiceConnection -Name "storage-conn" `
    -PrivateLinkServiceId $storageId -GroupId "blob"
 
New-AzPrivateEndpoint -ResourceGroupName "newrg-" `
    -Name "pe-storage-blob" -Location "eastus" `
    -Subnet $subnet -PrivateLinkServiceConnection $plsConn
Write-Host "Private Endpoint olusturuldu." -ForegroundColor Green
 

Private DNS Zone Bağlamak

PowerShell

$dnsZone = New-AzPrivateDnsZone -ResourceGroupName "newrg-" `
    -Name "privatelink.blob.core.windows.net"
 
New-AzPrivateDnsVirtualNetworkLink -ResourceGroupName "newrg- " `
    -ZoneName "privatelink.blob.core.windows.net" `
    -Name "blob-dns-link" `
    -VirtualNetworkId (Get-AzVirtualNetwork -Name "vpntest-vnet" -ResourceGroupName "vpntest").Id `
    -EnableRegistration
Write-Host "Private DNS Zone baglnadı." -ForegroundColor Green
 

Continue Reading PowerShell ile Azure Private Endpoint Yapılandırması