Перейти к основному содержимому

PowerShell Сниппеты

Полезные сниппеты для автоматизации задач в PowerShell.

Управление системой

Информация о системе

# Информация о системе
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, TotalPhysicalMemory

# Процессор
Get-WmiObject -Class Win32_Processor | Select-Object Name, MaxClockSpeed, NumberOfCores

# Диски
Get-WmiObject -Class Win32_LogicalDisk | Select-Object DeviceID, Size, FreeSpace, @{Name="FreePercent";Expression={[math]::Round(($_.FreeSpace/$_.Size)*100,2)}}

# Сетевые адаптеры
Get-NetAdapter | Where-Object Status -eq "Up" | Select-Object Name, LinkSpeed

Управление службами

# Список всех служб
Get-Service | Sort-Object Status, Name

# Остановка службы
Stop-Service -Name "ServiceName" -Force

# Запуск службы
Start-Service -Name "ServiceName"

# Изменение типа запуска
Set-Service -Name "ServiceName" -StartupType Manual

# Проверка статуса службы
$service = Get-Service -Name "ServiceName"
if ($service.Status -eq "Running") {
Write-Host "Service is running" -ForegroundColor Green
} else {
Write-Host "Service is not running" -ForegroundColor Red
}

Управление процессами

# Процессы по использованию памяти
Get-Process | Sort-Object WorkingSet -Descending | Select-Object -First 10 Name, @{Name="Memory(MB)";Expression={[math]::Round($_.WorkingSet/1MB,2)}}

# Завершение процесса
Get-Process -Name "ProcessName" | Stop-Process -Force

# Мониторинг процессов
while ($true) {
Clear-Host
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name, CPU, @{Name="Memory(MB)";Expression={[math]::Round($_.WorkingSet/1MB,2)}} | Format-Table
Start-Sleep -Seconds 2
}

Работа с файлами

Поиск и очистка

# Поиск больших файлов
Get-ChildItem -Path C:\ -Recurse -File |
Sort-Object Length -Descending |
Select-Object -First 20 FullName, @{Name="Size(MB)";Expression={[math]::Round($_.Length/1MB,2)}}

# Очистка временных файлов
$tempFolders = @(
"$env:TEMP",
"$env:LOCALAPPDATA\Temp",
"C:\Windows\Temp"
)

foreach ($folder in $tempFolders) {
if (Test-Path $folder) {
Get-ChildItem -Path $folder -Recurse -Force | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Write-Host "Cleaned: $folder" -ForegroundColor Green
}
}

# Поиск дублей файлов
function Find-DuplicateFiles {
param([string]$Path)

Get-ChildItem -Path $Path -Recurse -File |
Group-Object -Property Length |
Where-Object Count -gt 1 |
ForEach-Object {
$_.Group | Get-FileHash | Group-Object -Property Hash | Where-Object Count -gt 1
}
}

Backup скрипты

# Простой backup
function Backup-Folder {
param(
[string]$Source,
[string]$Destination
)

$date = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$backupPath = Join-Path $Destination "Backup_$date"

Write-Host "Creating backup: $backupPath" -ForegroundColor Yellow
Copy-Item -Path $Source -Destination $backupPath -Recurse -Force
Write-Host "Backup completed!" -ForegroundColor Green
}

# Инкрементальный backup
function Backup-Incremental {
param(
[string]$Source,
[string]$Destination
)

$lastBackup = Get-ChildItem -Path $Destination -Directory | Sort-Object CreationTime -Descending | Select-Object -First 1

if ($lastBackup) {
$changedFiles = Get-ChildItem -Path $Source -Recurse -File | Where-Object LastWriteTime -gt $lastBackup.CreationTime

if ($changedFiles) {
$date = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$backupPath = Join-Path $Destination "Incremental_$date"
New-Item -Path $backupPath -ItemType Directory

foreach ($file in $changedFiles) {
$relativePath = $file.FullName.Substring($Source.Length)
$destFile = Join-Path $backupPath $relativePath
$destDir = Split-Path $destFile -Parent

if (!(Test-Path $destDir)) {
New-Item -Path $destDir -ItemType Directory -Force
}

Copy-Item -Path $file.FullName -Destination $destFile
}

Write-Host "Incremental backup completed: $changedFiles.Count files" -ForegroundColor Green
} else {
Write-Host "No changes since last backup" -ForegroundColor Yellow
}
} else {
Backup-Folder -Source $Source -Destination $Destination
}
}

Сетевые операции

Сетевая диагностика

# Проверка подключения
function Test-NetworkConnectivity {
param([string[]]$Hosts)

foreach ($host in $Hosts) {
$result = Test-NetConnection -ComputerName $host -Port 443 -WarningAction SilentlyContinue
if ($result.TcpTestSucceeded) {
Write-Host "$host - OK" -ForegroundColor Green
} else {
Write-Host "$host - FAILED" -ForegroundColor Red
}
}
}

# Скан портов
function Scan-Ports {
param(
[string]$ComputerName,
[int[]]$Ports
)

foreach ($port in $Ports) {
$result = Test-NetConnection -ComputerName $ComputerName -Port $port -WarningAction SilentlyContinue
$status = if ($result.TcpTestSucceeded) { "Open" } else { "Closed" }
Write-Host "$ComputerName:$port - $status"
}
}

# Мониторинг трафика
Get-Counter -Counter "\Network Interface(*)\Bytes Total/sec" -SampleInterval 1 -MaxSamples 10

WiFi управление

# Список WiFi профилей
netsh wlan show profiles

# Экспорт WiFi профиля
netsh wlan export profile name="WiFiName" folder=C:\WiFiBackup

# Подключение к WiFi
netsh wlan connect name="WiFiName"

# Отключение от WiFi
netsh wlan disconnect

# Информация о текущем подключении
netsh wlan show interfaces

Автоматизация разработки

Git операции

# Массовое обновление репозиториев
function Update-AllRepos {
param([string]$BasePath)

Get-ChildItem -Path $BasePath -Directory | ForEach-Object {
$gitPath = Join-Path $_.FullName ".git"
if (Test-Path $gitPath) {
Write-Host "Updating: $($_.Name)" -ForegroundColor Yellow
Set-Location $_.FullName
git pull
Write-Host "Updated: $($_.Name)" -ForegroundColor Green
}
}
}

# Создание нового проекта
function New-Project {
param(
[string]$Name,
[string]$Type = "node"
)

$projectPath = Join-Path (Get-Location) $Name
New-Item -Path $projectPath -ItemType Directory
Set-Location $projectPath

switch ($Type) {
"node" {
npm init -y
New-Item -Name "src" -ItemType Directory
New-Item -Name "src\index.js" -ItemType File
"@echo off`nnode src/index.js" | Out-File -FilePath "run.bat" -Encoding ASCII
}
"python" {
New-Item -Name "src" -ItemType Directory
New-Item -Name "src\main.py" -ItemType File
New-Item -Name "requirements.txt" -ItemType File
"#!/usr/bin/env python3`nprint('Hello, World!')" | Out-File -FilePath "src\main.py" -Encoding UTF8
}
}

git init
".env`nnode_modules/`n__pycache__/`n*.pyc`n.DS_Store`nThumbs.db" | Out-File -FilePath ".gitignore" -Encoding UTF8

Write-Host "Project '$Name' created successfully!" -ForegroundColor Green
}

Docker операции

# Очистка Docker
function Clean-Docker {
Write-Host "Stopping all containers..." -ForegroundColor Yellow
docker stop $(docker ps -aq)

Write-Host "Removing all containers..." -ForegroundColor Yellow
docker rm $(docker ps -aq)

Write-Host "Removing unused images..." -ForegroundColor Yellow
docker image prune -af

Write-Host "Removing unused volumes..." -ForegroundColor Yellow
docker volume prune -f

Write-Host "Docker cleanup completed!" -ForegroundColor Green
}

# Мониторинг Docker
function Monitor-Docker {
while ($true) {
Clear-Host
Write-Host "=== Docker Containers ===" -ForegroundColor Cyan
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

Write-Host "`n=== Docker Images ===" -ForegroundColor Cyan
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"

Start-Sleep -Seconds 5
}
}

Системное администрирование

Управление пользователями

# Создание пользователя
function New-LocalUser {
param(
[string]$Username,
[string]$FullName,
[string]$Description
)

$password = Read-Host "Enter password" -AsSecureString
New-LocalUser -Name $Username -FullName $FullName -Description $Description -Password $password
Write-Host "User '$Username' created successfully!" -ForegroundColor Green
}

# Список пользователей
Get-LocalUser | Select-Object Name, Enabled, LastLogon

# Блокировка/разблокировка пользователя
Disable-LocalUser -Name "Username"
Enable-LocalUser -Name "Username"

Планировщик задач

# Создание задачи
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Scripts\backup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "2:00AM"
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 2)

Register-ScheduledTask -TaskName "DailyBackup" -Action $action -Trigger $trigger -Settings $settings -Description "Daily backup script"

# Список задач
Get-ScheduledTask | Where-Object State -eq "Ready" | Select-Object TaskName, State

# Запуск задачи
Start-ScheduledTask -TaskName "DailyBackup"

Логи и мониторинг

# Чтение логов событий
Get-WinEvent -LogName System -MaxEvents 10 | Select-Object TimeCreated, Id, LevelDisplayName, Message

# Мониторинг производительности
function Monitor-Performance {
$counters = @(
"\Processor(_Total)\% Processor Time",
"\Memory\Available MBytes",
"\LogicalDisk(_Total)\% Disk Time"
)

while ($true) {
$data = Get-Counter -Counter $counters -SampleInterval 1 -MaxSamples 1

Clear-Host
Write-Host "=== System Performance ===" -ForegroundColor Cyan
foreach ($sample in $data.CounterSamples) {
$value = [math]::Round($sample.CookedValue, 2)
Write-Host "$($sample.Path): $value"
}

Start-Sleep -Seconds 2
}
}

# Алерты по использованию ресурсов
function Monitor-Resources {
$cpuThreshold = 80
$memoryThreshold = 80
$diskThreshold = 90

while ($true) {
$cpu = (Get-Counter "\Processor(_Total)\% Processor Time").CounterSamples.CookedValue
$memory = (Get-Counter "\Memory\% Committed Bytes In Use").CounterSamples.CookedValue
$disk = (Get-Counter "\LogicalDisk(C:)\% Free Space").CounterSamples.CookedValue

if ($cpu -gt $cpuThreshold) {
Write-Host "WARNING: CPU usage is $([math]::Round($cpu, 2))%" -ForegroundColor Red
}

if ($memory -gt $memoryThreshold) {
Write-Host "WARNING: Memory usage is $([math]::Round($memory, 2))%" -ForegroundColor Red
}

if ((100 - $disk) -gt $diskThreshold) {
Write-Host "WARNING: Disk usage is $([math]::Round(100 - $disk, 2))%" -ForegroundColor Red
}

Start-Sleep -Seconds 30
}
}