לדלג לתוכן

2.2 פאוורשל סקריפט פתרון

פתרון לתרגילים מסכמים

  1. הבנת תנאים ולולאות:

  2. לולאת for שמדפיסה את המספרים מ-1 עד 10:

for ($i = 1; $i -le 10; $i++) {
    Write-Output $i
}
  • תנאי שבודק אם המשתנה $age גדול מ-18:
$age = 20
if ($age -gt 18) {
    Write-Output "Adult"
} else {
    Write-Output "Minor"
}
  • תנאי בוליאני שבודק את המשתנה $score:
$score = 85
if ($score -gt 90) {
    Write-Output "A"
} elseif ($score -gt 80 -and $score -le 90) {
    Write-Output "B"
}
  1. הגדרת פונקציות:

  2. פונקציה שמחזירה את סכום שני מספרים:

function Add-Numbers {
    param (
        [int]$a,
        [int]$b
    )
    return $a + $b
}

$sum = Add-Numbers -a 5 -b 10
Write-Output "Sum: $sum"
  • פונקציה שמחזירה את המילה הפוכה:
function Reverse-String {
    param (
        [string]$word
    )
    return -join ($word.ToCharArray() | [Array]::Reverse())
}

$reversedWord = Reverse-String -word "PowerShell"
Write-Output $reversedWord
  1. סקריפטים ב-PowerShell:

  2. סקריפט שמקבל שני פרמטרים ושומר את הטקסט בקובץ:

param (
    [string]$filename,
    [string]$text
)

Set-Content -Path $filename -Value $text
$content = Get-Content -Path $filename
Write-Output $content
  • להריץ את הסקריפט, יש ליצור קובץ בשם script.ps1 ולהריץ אותו ב-PowerShell עם:
.\script.ps1 -filename "C:\path\to\file.txt" -text "Hello, World!"
  1. קבלת ארגומנטים לסקריפט:

  2. סקריפט שמקבל שם ומשפחה ומדפיס את השם המלא:

$firstName = $args[0]
$lastName = $args[1]
Write-Output "$firstName $lastName"
  • להריץ את הסקריפט עם:
.\script.ps1 "John" "Doe"
  1. שימוש ב-.NET ב-PowerShell:

  2. הצגת התאריך והשעה הנוכחיים בעזרת System.DateTime:

$dateTime = [System.DateTime]::Now
Write-Output $dateTime
  • הורדת HTML מאתר אינטרנט בעזרת System.Net.WebClient:
$webClient = New-Object System.Net.WebClient
$htmlContent = $webClient.DownloadString("https://example.com")
Write-Output $htmlContent
  • בדיקת קיום קובץ בעזרת System.IO.File:
$filePath = "C:\path\to\file.txt"
if (-Not (Test-Path $filePath)) {
    New-Item -Path $filePath -ItemType File
    Write-Output "File created."
} else {
    Write-Output "File exists."
}
  1. שימוש בלולאות ובתנאים יחד:

  2. לולאת for שבודקת אם מספר הלולאה זוגי או אי-זוגי:

for ($i = 1; $i -le 10; $i++) {
    if ($i % 2 -eq 0) {
        Write-Output "$i is Even"
    } else {
        Write-Output "$i is Odd"
    }
}