Скрипты для автоматизации задач в windows

Время на прочтение4 мин

Количество просмотров26K

В этой статье рассмотрим почему мы все любим Powershell на паре рабочих примеров. Все это будет полезно при инвентаризации, поиске конкретного компьютера и прочих делах. Powershell оборудован удобными и запоминающимися командлетами, автодополнение всего и интуитивные названия делают его наверное самым простым в освоении языком.

В этом руководстве рассмотрим несколько крутых по мнению автора команд и расскажем почему это круто. Начнем со снипетов.

Полезные снипеты:

Заносим компьютер в TrustedHosts

Пригодится при подключении к серверу по WinRm. Команда перезапишет предыдущее значение, будьте осторожны, добавляйте ip или имена хостов через запятую. Если все ваши хосты находятся в AD, трогать этот файл не нужно.

Set-Item WSMan:\localhost\Client\TrustedHosts -Value '192.168.0.1'

Wildcard тоже работает, если не хотите каждый раз добавлять новый хост в TrustedHosts.

Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'

Храним пароль в зашифрованном виде в файле:

Пригодится для автоматизации, сильно облегчает жизнь при выполнении скриптов из планировщика, но при этом пароль хранится в безопасном виде. 

Если выполнять скрипты из под зашедшего пользователя, будут использоваться креды этого пользователя.

Read-Host -AsSecureString | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath .\Password.txt

Забираем зашифрованный пароль из файла:

$Password = Get-Content C:\Password.txt | ConvertTo-SecureString

Тоже самое можно проделать и с Credentials, заменим Read-Host на Get-Credential.

Get-Credential | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath .\Credential.txt

Получаем дату последней загрузки ОС.

(gcim win32_operatingsystem).LastBootUpTime

Тем же самым способом получаем еще и аптайм.

Get-CimInstance Win32_operatingsystem -ComputerName $computers |
Select-Object LastBootUpTime,
@{Name="Uptime";Expression = {(Get-Date) - $_.LastBootUptime}} 

Получаем список установленных программ:

Именно программ, а не компонентов:


Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |  Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize

Получаем список дисков, в том числе сетевых и свободное место на них

Get-PSDrive -PSProvider filesystem | where-object {$_.used -gt 0} |
Select-Object -property Root,@{name="Size";expression={($_.used+$_.free)/1GB -as [int]}},
@{name="Used";expression={($_.used/1GB) -as [int]}},
@{name="Free";expression={($_.free/1GB) -as [int]}} 

Останавливаем процесс по его имени.

В этом примере останавливаем Chrome. Wildcard тоже подойдет, если хотите завершить всё.

Get-Process -Name "chrome" | Stop-Process

Копируем настройки доступа к папкам на дочерние папки

Пригодится, если вам захочется отобрать или дать права на пользование к папке и всем подпапкам у группы пользователей или у пользователя. Команда рекурсивно, снизу вверх копирует права на чтение и запись.

Копируем ACL у папки:

$Acl = Get-Acl -Path C:\folder\

Вставляем ACL на все файлы и подпапки:

Get-ChildItem -Path C:\Folder\ -Recurse | Set-Acl $Acl 

Полезные скрипты:

Вот тут начинается самое страшное веселье. Если вам нужно провести инвентаризацию, будет очень полезно глянуть. Если ваши компьютеры не в AD, то скрипт станет немного сложнее, итерировать придется по заранее составленному файлу, а пароли нужно будет брать из файла или через Get-Credential. Вся разница:

C AD:

$ADComputers = (Get-ADComputer -filter *).DNSHostName

Без AD:

$Credentials = Get-Credential
$Computers = Get-Content -Path C:\servers.txt

Получаем аптайм дату последней загрузки каждого из компьютеров в AD:


$ADComputers = (Get-ADComputer -filter *).DNSHostName

foreach ($i in $ADComputers) {
 
    Invoke-Command $i {
        Get-CimInstance Win32_operatingsystem |
        Select-Object LastBootUpTime,
        @{Name="Uptime";Expression = {(Get-Date) - $_.LastBootUptime}} 
    } 
 
}

Получаем все установленные программы на всех компьютерах AD:

$ADComputers = (Get-ADComputer -filter *).DNSHostName
foreach ($i in $ADComputers) {
 
    Invoke-Command -computername $i {
        gcim win32_product -computername $env:computername | Sort-Object -property Vendor,Name | Select-Object -property Vendor,Name, Caption 
    } 
 
}

Тоже самое можно будет получить и для компонентов, подставив в Invoke-Command:

Get-WindowsFeature | Where-Object -Property "Installed" -EQ "Installed"

Получаем компьютеры, где запущен нужный нам процесс:

Если вы забыли на каком компьютере запущена та или иная программа, можно получить её таким способом. Рассмотрим на примере браузера:

$ADComputers = (Get-ADComputer -filter *).DNSHostName
foreach ($i in $ADComputers) {
 
    Invoke-Command -computername $i {
        Get-Process -Name "Chrome"  -ErrorAction SilentlyContinue
    } 
 
}

Убить браузер можно будет так же легко, как и получить процесс:

$ADComputers = (Get-ADComputer -filter *).DNSHostName
foreach ($i in $ADComputers) {
 
    Invoke-Command -computername $i {
        Get-Process -Name "Chrome" | Stop-Process -ErrorAction SilentlyContinue
    } 
 
}

Получаем компьютеры, где установлена конкретная программа:

Кокретно в этом случае Java. Поможет при проведении инвентаризации можно будет посмотреть имена компьютеров где она была установлена.

$ADComputers = (Get-ADComputer -filter *).DNSHostName
foreach ($i in $ADComputers) {
 
    Invoke-Command -computername $i {
        gcim win32_product -computername $env:computername | Select-String -Pattern "Java" -AllMatches | Sort-Object -property Vendor,Name | Format-Table -ErrorAction SilentlyContinue
 
    } 
 
}

Если у вас возникнут предложения, будем рады добавить их в эту статью. Надеемся, эти примеры были для вас полезны.

Предлагаем обновлённый тариф UltraLite Windows VDS за 99 рублей с установленной Windows Server 2019 Core.

Навигация по странице

  1. Как сделать и запустить скрипт PowerShell?
  2. Как запустить скрипт в PowerShell?
  3. Как разрешить выполнение неподписанного скрипта PowerShell?
  4. Как запустить скрипт PowerShell в фоновом режиме?
  5. Как запустить скрипт через PowerShell с параметрами?
  6. Как запустить скрипт PowerShell с помощью ярлыка?
  7. Полезные сценарии для Windows
  8. Что такое командные скрипты Windows?
  9. Что такое Bat-скрипты Windows?
  10. Что такое исполняемые скрипты Windows?
  11. Какое расширение имеют файлы скриптов PowerShell?
  12. Какие скрипты PowerShell используются администраторами?

Выполнение скриптов в PowerShell

PowerShell представляет собой новую командную оболочку для операционной системы Windows, созданную Microsoft с целью полного замещения и улучшения cmd. Эта оболочка уже включена в состав операционных систем Windows 7 и выше. Если у вас старая версия операционной системы или вы хотите загрузить более новую версию PowerShell. Windows — операционная система, пользующаяся огромной популярностью среди миллионов пользователей по всему миру. В ее арсенале множество функций и возможностей, однако некоторые из них остаются недостаточно известными обычным пользователям. В данной статье мы расскажем о нескольких полезных сценариях, способных сделать вашу работу с Windows более эффективной и удобной.

Политика исполнения PowerShell-скриптов представляет собой механизм безопасности, управляющий условиями загрузки конфигурационных файлов и запуска сценариев в данной среде. Её основное предназначение — предотвращение выполнения потенциально вредоносных сценариев.

Полезные скрипты PowerShell для Windows

Как сделать и запустить скрипт PowerShell

Создать скрипт PowerShell довольно просто. Вот шаги, которые вы можете выполнить, чтобы создать свой первый скрипт:

1. Откройте редактор PowerShell ISE:

PowerShell ISE (Integrated Scripting Environment) предоставляет удобную среду для написания и отладки скриптов. Вы можете его найти в меню «Пуск» (Start) под разделом «Стандартные» (Standard) или выполнить команду `PowerShell_ise` в командной строке.

2. Напишите свой скрипт:

В окне редактора PowerShell ISE напишите свой скрипт. Ниже приведен пример простого скрипта, который выводит «Hello, World!» в консоль:

Write-Host «Hello, World!»

3. Сохраните скрипт:

  • Нажмите `Ctrl + S` или выберите «Файл» (File) -> «Сохранить» (Save).
  • Укажите имя файла и добавьте расширение `.ps1` (например, `MyScript.ps1`).

4. Запустите скрипт:

  • Выберите весь текст скрипта.
  • Нажмите `F5` или выберите «Запустить сценарий» (Run Script) в PowerShell ISE.

Примеры более сложных скриптов:

#Скрипт, создающий новую папку:

$folderPath = «C:\Path\To\NewFolder»

New-Item -ItemType Directory -Path $folderPath

#Скрипт, удаляющий все файлы старше 7 дней в папке:

$folderPath = «C:\Path\To\Folder»

$limitDate = (Get-Date).AddDays(-7)

Get-ChildItem $folderPath | Where-Object { $_.LastWriteTime -lt $limitDate } | Remove-Item

#Скрипт, проверяющий статус службы:

$serviceName = «wuauserv»

$serviceStatus = Get-Service -Name $serviceName | Select-Object Status

Write-Host «The status of service $serviceName is: $($serviceStatus.Status)»

Ваши скрипты могут включать более сложные команды, использовать условия, циклы и вызывать функции. Как только вы освоите основы, вы сможете создавать более мощные и гибкие скрипты PowerShell.

Полезные скрипты PowerShell для Windows

Скрипты для Windows — не просто строки кода, а волшебные ключи, открывающие дверь в мир автоматизации. В руках умелого пользователя они становятся инструментом, способным не только сэкономить время, но и превратить рутинные задачи в захватывающее путешествие по потокам байтов и командам.

Как запустить скрипт в PowerShell?

Существует несколько способов запуска скрипта, вот основные из них:

  1. Запустить оболочку PowerShell и выполнить в ней скрипт, указав путь к файлу и его имя (например, C:\Scripts\test.ps1) или перейдя в каталог скрипта командой cd C:\Scripts и выполнить его с помощью команды .\test.ps1.
  2. Оболочку можно найти и запустить разными способами. Один из них — через меню «Пуск». Для Windows 7 пройдите по следующему пути: «Все программы» — «Стандартные» — «Windows PowerShell» и запустите оболочку «Windows PowerShell». Для Windows 10 найдите группу по букве «W» и в ней выберите «Windows PowerShell».
  3. Запустить «Интегрированную среду сценариев Windows PowerShell ISE», которая представляет собой среду разработки, позволяющую редактировать и отлаживать скрипты PowerShell. Откройте программу, выберите «Открыть» или в меню Файл выберите «Открыть» и укажите нужный скрипт, затем нажмите F5 или кнопку «Выполнить скрипт». Поиск Windows PowerShell ISE можно осуществить так же, как и оболочки PowerShell, через меню «Пуск».
  4. Запустить стандартный командный интерфейс и ввести следующую команду:

PowerShell -file <имя_скрипта> (например: PowerShell -file myscript.ps1)

Если вы ранее не запускали скрипты PowerShell, возможно, вы получите сообщение о том, что файл <имя_скрипта> не может быть загружен, так как выполнение скриптов запрещено для данной системы. В этом случае введите «get-help about_signing» для получения дополнительной информации. Это связано с безопасностью и предотвращением случайного выполнения вредоносного кода, поэтому все скрипты должны быть подписаны цифровой подписью.

Как разрешить выполнение неподписанного скрипта PowerShell?

  • В оболочке PowerShell перед запуском скрипта выполните следующую команду для разрешения выполнения неподписанных скриптов в текущем сеансе оболочки:

Set-ExecutionPolicy RemoteSigned -Scope Process

  • При запуске из стандартного командного интерфейса используйте параметр -executionpolicy, например:

PowerShell -executionpolicy RemoteSigned -file <имя_скрипта>

Оба способа устанавливают политику только для текущего сеанса, при этом политика безопасности выполнения скриптов PowerShell, установленная в реестре, остается неизменной. Если вы хотите изменить политику безопасности выполнения скриптов «навсегда», используйте следующий способ:

  • Разрешить выполнение навсегда: запустите оболочку PowerShell от имени «Администратора» и выполните команду:

Set-ExecutionPolicy RemoteSigned

Однако рекомендуется избегать этого способа, чтобы не подвергать ваш компьютер возможным угрозам, поскольку это разрешает выполнение всех скриптов всегда.

Примечание: Если скрипт был загружен из интернета, чтобы избежать запроса на подтверждение выполнения, используйте параметр Bypass вместо RemoteSigned — это полное отключение любых запросов и предупреждений.

Полезные скрипты PowerShell для Windows

Как запустить скрипт PowerShell в фоновом режиме?

Для этого используйте параметр -WindowStyle, который может принимать значения: Normal, Minimized, Maximized и Hidden. Чтобы запустить неподписанный скрипт в фоновом режиме, выполните команду:

PowerShell -executionpolicy RemoteSigned -WindowStyle Hidden -file <имя_скрипта>

Также при желании вы можете добавить -NonInteractive, чтобы скрипт не задавал никаких вопросов. Таким образом, скрипт выполнится незаметно для пользователя. Однако будьте внимательны, используя этот способ.

Скрипты PowerShell Windows

Как запустить скрипт через PowerShell с параметрами?

Запуск осуществляется аналогично запуску обычной программы или bat-файла с параметрами. Например, чтобы запустить скрипт с параметрами из командной строки, используйте следующую команду:

PowerShell -executionpolicy RemoteSigned -file <имя_скрипта> param1 param2 «еще один текстовый параметр«

В самом скрипте параметры могут быть получены так:

param ($var1, $var2, $var3)

echo $var1, $var2, $var3

В интегрированной среде PowerShell ISE скрипт с параметрами можно запустить аналогично, используя область команд.

Выполнение скриптов в PowerShell

Как запустить скрипт PowerShell с помощью ярлыка?

Это можно сделать двумя способами:

  1. Создать файл bat/cmd, в котором прописать команду для запуска скрипта (с параметрами, как описано выше).
  2. Создать ярлык на PowerShell, который находится в папке c:\Windows\System32\WindowsPowerShell\v<версия>\. В свойствах ярлыка в поле «Объект» добавьте необходимые параметры.

Таким образом, например, чтобы запустить скрипт PowerShell при входе пользователя, просто создайте ярлык, как описано во втором пункте, и поместите его в автозагрузку. Также создание ярлыка с использованием одного из вышеописанных методов позволяет легко запускать скрипт от имени администратора или от имени любого другого пользователя, как обычную программу.

Скриптовый язык PowerShell — мощный инструмент для решения различных задач. Однако следует использовать его с осторожностью, поскольку он может быть использован не только для полезных, но и для вредоносных целей. Будьте внимательны при работе с ним.

Скрипты PowerShell для администратора

Полезные сценарии для Windows

1. Скрипт выключения Windows (или перезагрузки):

Простейшая операция выключения компьютера. Откройте блокнот и введите:

shutdown -s -t 0

Сохраните файл с расширением *.cmd* (например, *shutdown.cmd*). При запуске этого файла компьютер выключится. Замените «-s» на «-r» для перезагрузки. Параметр «-t» устанавливает таймер; в данном случае, он равен 0 секунд, но можно установить, например, на 60 для выключения через 60 секунд.

2. Удаление ненужных приложений:

С помощью следующего скрипта можно удалить предустановленные приложения:

get-appxpackage -name *APPNAME* | remove-appxpackage

Замените *APPNAME* на название ненужного приложения. Хотя удаление можно выполнить стандартным способом или через программы, этот скрипт делает процесс более удобным.

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

Воспользуйтесь PowerShell для борьбы с медленными процессами. Выведите все службы:

Get-Service

Или получите информацию о конкретной службе с кодовым именем *NAME*:

Get-Service *NAME*

Создайте файл, который закрывает процессы с повышенным потреблением ресурсов:

Stop-Service -Name *ANTIVIRUS*

Stop-Service -Name *BROWSER*

Замените *ANTIVIRUS* и *BROWSER* на соответствующие названия.

4. Переименование группы файлов:

Решите проблему однотипных файлов с помощью скрипта группового переименования:

$path = «$comp\desktop\journey\russia»

$filter = ‘*.jpg’

get-childitem -path $path -filter $filter | rename-item -newname {$_.name -replace ‘HGNMD’,’RUSSIA’}

Укажите путь, расширение и выполните замены в строке.

5. Поиск файлов:

Используйте PowerShell для поиска файлов в директории:

Get-Childitem C:\Windows\*.log

Для более сложного поиска в подпапках:

Get-ChildItem C:\Windows\* -Include *.log -Recurse -Force

6. Справка:

Пользуйтесь командой *Get-Help* для получения информации:

Get-Help Services

Для более подробной справки по конкретной команде:

Get-Help —Name *CMDLET*

7. Получение информации о системе:

Используйте PowerShell для получения данных о системе, например, уровне заряда аккумулятора:

Add-Type -AssemblyName System.Windows.Forms

[Windows.Forms.PowerStatus].GetConstructor(‘NonPublic, Instance’, $null, [Type[]]@(), $null ).Invoke($null)

Информация об архитектуре процессора удаленного компьютера:

[PSObject].Assembly.GetType(‘System.Management.Automation.PsUtils’).GetMethod(‘GetProcessorArchitecture’, [Reflection.BindingFlags]40).Invoke($null, @())

Проверка прав администратора текущего пользователя:

[PSObject].Assembly.GetType(‘System.Management.Automation.Utils’).GetMethod(‘IsAdministrator’, [Reflection.BindingFlags]40).Invoke($null, @())

Эти простые и полезные сценарии помогут вам эффективнее управлять вашей системой Windows.

Командные скрипты Windows

Это общий термин, который включает в себя различные типы скриптов и командных файлов, используемых в операционной системе Windows для автоматизации задач. Включают в себя как скрипты на языке командной строки (например, скрипты CMD), так и на более современных языках, таких как PowerShell. Например, Bat-скрипты (*.bat), PowerShell-скрипты (*.ps1), а также другие сценарии, созданные для автоматизации определенных задач.

Bat-скрипты Windows

Bat-скрипты, или файлы пакетных команд (Batch-файлы), представляют собой текстовые файлы, содержащие команды и инструкции для выполнения в командной строке Windows. Основаны на языке пакетных команд (Batch scripting language). Расширение файла: *.bat* (например, *myscript.bat*).

Пример простого bat-скрипта:

«`batch

@echo off

echo Hello, World!

pause

Выполняемые скрипты Windows

Это скрипты, которые могут быть выполнены в среде операционной системы Windows и обычно предназначены для автоматизации различных задач. Включают в себя bat-скрипты (командные файлы), PowerShell-скрипты, а также другие типы скриптов, которые можно выполнять в Windows. Общее отличие между bat-скриптами и PowerShell-скриптами заключается в языке программирования, используемом для написания команд и инструкций. Bat-скрипты используют язык пакетных команд, который является устаревшим и имеет ограниченные возможности по сравнению с PowerShell, который представляет более современный и мощный язык с разнообразными функциональными возможностями для автоматизации задач в Windows.

Какое расширение имеют файлы скриптов PowerShell

PowerShell-скрипты имеют расширение *.ps1*, и для их выполнения часто требуется предварительная настройка политики выполнения скриптов (Execution Policy), чтобы разрешить запуск скрипта через PowerShell в системе.

Скрипты PowerShell для администратора

PowerShell — мощный инструмент для сисадминов Windows, предоставляя широкий набор команд и сценариев для автоматизации и управления системой. Ниже приведены несколько примеров PowerShell-скриптов, которые могут быть полезны администраторам:

1. Создание резервной копии файлов:

$sourcePath = «C:\Path\To\Source»

$destinationPath = «D:\Backup»

$timestamp = Get-Date -Format «yyyyMMddHHmmss»

$backupFolder = «$destinationPath\Backup_$timestamp»

Copy-Item -Path $sourcePath -Destination $backupFolder -Recurse

2. Мониторинг дискового пространства:

$threshold = 80

$disks = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }

foreach ($disk in $disks) {

$freeSpacePercentage = [math]::Round(($disk.FreeSpace / $disk.Size) * 100, 2)

$diskLetter = $disk.DeviceID

if ($freeSpacePercentage -lt $threshold) {

Write-Host «Warning: Disk $diskLetter is running low on free space ($freeSpacePercentage%)»

# Можно добавить уведомление администратора

}

}

3. Создание нового пользователя:

$username = «NewUser»

$password = ConvertTo-SecureString «SecurePassword123» -AsPlainText -Force

$fullname = «New User»

$description = «Description of the new user»

$ou = «OU=Users,DC=Domain,DC=com»

New-ADUser -SamAccountName $username -UserPrincipalName «$username@domain.com» -Name $fullname -GivenName $fullname -Surname $username -Description $description -AccountPassword $password -Enabled $true -PassThru -Path $ou

4. Мониторинг событий в журнале событий:

$logName = «System»

$events = Get-WinEvent -LogName $logName -MaxEvents 10

foreach ($event in $events) {

Write-Host «Event ID $($event.Id): $($event.Message)»

}

5. Обновление всех установленных модулей PowerShell:

Get-Module -ListAvailable | ForEach-Object {

Update-Module -Name $_.Name -Force

}

6. Удаление временных файлов в системной директории:

$tempPath = [System.IO.Path]::GetTempPath()

Remove-Item «$tempPath\*» -Force

7. Создание отчета о состоянии служб:

$services = Get-Service | Select-Object DisplayName, Status, StartType

$services | Export-Csv -Path «C:\Path\To\ServiceReport.csv» -NoTypeInformation

8. Настройка правил брандмауэра:

New-NetFirewallRule -DisplayName «Allow-SSH» -Direction Inbound -Protocol TCP -LocalPort 22 -Action Allow

9. Удаление неиспользуемых профилей пользователей:

$inactiveDays = 90

$userProfiles = Get-WmiObject Win32_UserProfile | Where-Object { $_.Special -eq $false }

foreach ($profile in $userProfiles) {

$lastUseDate = $profile.LastUseTime

$difference = (Get-Date) — $lastUseDate

if ($difference.Days -ge $inactiveDays) {

Remove-WmiObject -InputObject $profile -Confirm:$false

Write-Host «User profile $($profile.LocalPath) deleted.»

}

}

Эти примеры предоставляют общее представление о том, как PowerShell может использоваться администраторами для автоматизации различных задач в Windows-среде. Помните, что некоторые команды могут потребовать выполнения от имени администратора.

Для вызова скриптов PowerShell, вы можете использовать команду `Invoke-Expression` или просто указать путь к файлу скрипта. Предположим, у вас есть следующие скрипты: `ClearDisk.ps1`, `InstallPrograms.ps1`, `BackupScript.ps1`, и `UpdateSystem.ps1`.

1. Скрипт очистки диска (ClearDisk.ps1):

# ClearDisk.ps1

# Ваш код для очистки диска

# Пример: удаление временных файлов

Remove-Item -Path «$env:TEMP\*» -Recurse -Force

Как вызвать:

# Используйте Invoke-Expression

Invoke-Expression -Command «.\ClearDisk.ps1»

# Или просто указывайте путь к файлу скрипта

.\ClearDisk.ps1

2. Скрипт автоматической установки программ (InstallPrograms.ps1):

# InstallPrograms.ps1

# Ваш код для автоматической установки программ

# Пример: установка программы Chocolatey и установка пакетов

Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1’))

choco install packageName -y

Как вызвать:

# Используйте Invoke-Expression

Invoke-Expression -Command «.\InstallPrograms.ps1»

# Или просто указывайте путь к файлу скрипта

.\InstallPrograms.ps1

3. Скрипт резервного копирования (BackupScript.ps1):

# BackupScript.ps1

# Ваш код для создания резервной копии

# Пример: копирование файлов в другую директорию

$sourcePath = «C:\Path\To\Source»

$destinationPath = «D:\Backup»

Copy-Item -Path $sourcePath -Destination $destinationPath -Recurse

Как вызвать:

# Используйте Invoke-Expression

Invoke-Expression -Command «.\BackupScript.ps1»

# Или просто указывайте путь к файлу скрипта

.\BackupScript.ps1

4. Скрипт автоматического обновления системы (UpdateSystem.ps1):

# UpdateSystem.ps1

# Ваш код для автоматического обновления системы

# Пример: обновление всех установленных модулей PowerShell

Get-Module -ListAvailable | ForEach-Object {

Update-Module -Name $_.Name -Force

}

Как вызвать:

# Используйте Invoke-Expression

Invoke-Expression -Command «.\UpdateSystem.ps1»

# Или просто указывайте путь к файлу скрипта

.\UpdateSystem.ps1

Убедитесь, что вы находитесь в той же директории, что и ваши скрипты, или укажите полный путь к файлу скрипта.

В этой статье мы коснулись всех аспектов создания, запуска и использования скриптов в Windows. Надеемся, что эти советы и примеры помогут вам освоить этот увлекательный мир автоматизации и сделают вашу работу более эффективной и приятной.

What is PowerShell?

You might know PowerShell as the improved command prompt version of Microsoft Windows, but PowerShell is more than that. It is also a scripting language that can be used for automation, and in this article we’ll show you how to automate tasks with PowerShell. PowerShell is built on the .Net CLR (Common Language Runtime), and as a scripting language, it can be used for automating the management of systems. You can use PowerShell to automate boring or repetitive IT tasks whether they are simple or complex. PowerShell even has backward compatibility with the command prompt, meaning you can type a CMD command in PowerShell and it will execute the command and return the output.

automate-tasks-with-powershell

PowerShell is everywhere on Windows clients and servers and in macOS, Linux, and Cloud environments. Hence, it makes sense to use PowerShell to automate your day to day tasks. PowerShell is installed by default on your Windows system and you can easily install it on our Linux systems as well.

Why automate with PowerShell?

As an automation language, PowerShell has a wide array of modules to deploy and manage multiple ecosystems and technologies like Azure, Exchange, SQL, and many other third parties like AWS, VMWare, GCP, etc.

Using PowerShell you can automate tasks such as managing Active Directory users, managing and building Virtual Machines in Hyper-V, generating reports, monitoring performance, sending emails, etc. Automation with PowerShell is executing your commands via a script; those commands you type every day in PowerShell to do something. You can also use your PowerShell scripts and run them with Task Scheduler at desired times of the day.

PowerShell in Windows comes with the PowerShell ISE (Integrated Scripting Environment), which can help you write, test, and debug scripts in a GUI editor. The PowerShell ISE has some benefits when writing your scripts like syntax coloring, tab completion, and context-sensitive help. Of course, there are some other editors like Visual Studio Code, for example, that you can use. Using a GUI editor to create and test your scripts will make it easy to automate with PowerShell. There are even online resources like https://tio.run/#powershell where you can try some PowerShell commands (not like in Windows but is helpful).

How to create a PowerShell Script?

If you have used PowerShell, you have already executed commands to Get or Set configurations in Windows. Creating a script is saving those commands in a .ps1 file. A .ps1 file is a file that contains a script that is to be executed by PowerShell such as Get-Help. That is an easy-to-remember command that is not worth saving to a .ps1 file, but maybe Get-Date -DisplayHint Date is worth saving. We will see some more complex commands to save in .ps1 files later.

Note that by default in Windows, the default setting to execute scripts in PowerShell is not to allow scripts to run. PowerShell is enforcing its Execution Policy, which is Restricted by default. To check the execution policy, you can type Get-ExecutionPolicy. Also, check the help command in PowerShell by typing get-help set-executionpolicy. Finally, if you want to execute PowerShell scripts, you can change the execution policy by typing set-executionpolicy unrestricted or set-executionpolicy remotesigned depending on your requirements.

When you start to write these scripts, you might add one or more commands, and then you start scripting (which is writing a series of commands that can be executed) in PowerShell and saving your commands or tasks in a ps1 file.

A basic PowerShell script can be, for example:

Write-Host “Hello, Admin!”
Write-Host “Today is:”
Get-Date -DisplayHint Date

The output will display the Write-Host text strings and the date when you execute the command.

Or maybe something more advanced like installing a Windows Server role, for example:

Install-WindowsFeature -Name “Windows-Server-Backup” -IncludeAllSubFeature -IncludeManagementTools

The result will be that the Windows Server Backup role will be installed on the Windows system.

How to automate a simple task with PowerShell?

Automation might seem complicated but think of it as a series of steps executed in a system to reduce your input. A simple example to automate with PowerShell is to check the available Disk Space of a system:

Get-CimInstance -ClassName Win32_LogicalDisk -Filter “DriveType=3” | Measure-Object -Property FreeSpace,Size -Sum |
Select-Object -Property Property,Sum | `
Export-CSV C:\Users\Administrator\Downloads\Computer-Storage.csv -NoTypeInformation -Encoding UTF8

The output should be a new CSV file containing the available disk space of a system and the total space.

Or maybe you want to automate a report that shows if a user password expired. We can write something like the following:

Get-ADUser -filter * -properties PasswordLastSet, PasswordExpired | Sort Name |
Select Name, PasswordLastSet, PasswordExpired | `
Export-CSV C:\Users\Administrator\Downloads\Users.csv -NoTypeInformation -Encoding UTF8

The output should be a CSV file with all the users in Active Directory with their names when the password was last set and if the password is expired.

With the previous two examples, we can start querying for system information and status to understand how our systems are performing or just retrieving data on a time basis. There might be other use cases depending on your environment. For example, monitor Azure AD sign-in logs, check privileged group membership in Active Directory, expired passwords, users with the password never expire tick, etc.

You should start seeing the benefits of automating these sysadmin tasks with PowerShell. You should avoid complex scripts that do multiple tasks in one execution as a best practice. It might be challenging to debug and troubleshoot later if you have issues or need to update or modify the scripts. Also, remember to always comment on your scripts to remember what each line of code does or if someone else will be expanding your script, it will be beneficial to know what each piece of line does.

If you want to execute these scripts at a specific time automatically, just set a task in Task Scheduler and check your daily reports; no more typing the same commands to get your data every day.

How to create a task in Task Scheduler?

There’s a tool to run tasks automatically called Task Scheduler on Windows operating systems. The system and applications will use Task Scheduler to execute and run processes like updates, disk cleanup, backups, etc. but we can take advantage and automate with PowerShell
and schedule our scripts to execute at a particular day and time.

Follow these steps to create a Basic Task in Task Scheduler:
a. Click on the Windows button on the lower-left corner of your screen.
b. Type in the search box Task Scheduler.
c. Click on the Task Scheduler application.
d. On the Task Scheduler window, click on the Task Scheduler Library.
e. Right-click and select Create Basic Task.
f. Type a name for your task in the Name text box, optionally a Description, and click Next.
g. On the Task Trigger window, select weekly under When do you want the task to start?
h. Click Next to continue.
i. Choose a Start Date and Time on the Weekly window.
j. Select the Days you want the task to run and click Next.
k. Under the Action Window, select the Start a program radio button and click Next.
l. Now, here, we need to select the Powershell executable in the Program/Script by clicking the textbox click on the Browse button.
m. Browse to C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
n. In the Add arguments, you select the script location entering the path.
o. Click Next and Finish.

You can also edit the task once it is created or delete it if no longer needed.

Automate with PowerShell with security in mind

When creating your scripts as an Administrator, you want to automate with PowerShell with security in mind. You need to develop and test your scripts in a lab environment before using them in a production environment. Also, keep in mind that your Group Policy could require that your scripts are digitally signed before they can be executed. To fix this, either digitally sign the scripts or simply remove that requirement (less secure).

To check on these PowerShell policies, open Group Policy Editor and select the Group Policy to edit and navigate to Computer Configuration\Policies\Administrative Templates\Windows Components\Windows PowerShell. You will see different policies to manage PowerShell. Note that you can also apply them at the User level. For example, check out the Turn On Script Execution policy setting, and in the dropdown, you will see the three different options. RemoteSigned is Microsoft’s recommendation.

But setting one of these policies is not a security mechanism since there are some ways to bypass PowerShell execution Policies. Often, you’ll see a debate online on the best way to implement PowerShell Execution Policies.

Other ways to automate with PowerShell

With Windows PowerShell, you can use Desired State Configuration (DSC), which is a feature that helps sysadmins to do some advanced automation and specify the configuration of a machine. Think of it as having ten or a hundred Windows systems and setting the same setup to all.

What is PowerShell DSC?

With virtual machines in the cloud, physical servers and VMs being hosted on-premises, administrators have difficulty having a standard environment with the same baseline. Here is where DSC with its declarative model comes to the rescue to provide a way for system configuration management. That way, we can decide how our systems are to be configured with the help of PowerShell and the Windows Workflow engine.

One of the benefits of Desired State Configuration is to simplify your tasks by configuring any number of devices automatically.

There’s a lot of information related to DSC that is worth doing a Google search to find out more on how to use it and how it can apply to your use case.

How to learn to automate with PowerShell?

With PowerShell scripts on multiple websites on the Internet, one might be asking how to learn to automate with PowerShell? ServerAcademy.com has an entire module on Administration and Automation with Windows PowerShell that will get you started with the basics of PowerShell up to the use of PowerShell Desired State Configuration (DSC) Basics.

Conclusion

PowerShell is an excellent tool for system administration and is not going away, so it makes sense to learn its power to make your life easier as a sysadmin. Even information security professionals are learning how to use it to discover vulnerabilities or misconfiguration and secure system environments.

#статьи


  • 0

Автоматизируем рутину в Windows с помощью скриптов.

Иллюстрация: Оля Ежак для Skillbox Media

Филолог и технарь, пишет об IT так, что поймут даже новички. Коммерческий редактор, автор технических статей для vc.ru и «Хабра».

На Windows часто возникают рутинные задачи, которые хочется автоматизировать. Например, почистить временные файлы, забэкапить важные документы или запустить одним кликом несколько приложений. Для этого есть простой инструмент — BAT-файлы (в простонародье «батники»). В этой статье научимся разрабатывать простые скрипты и запускать их по расписанию.

Эксперт

CTO Flocktory, программный директор профессии «DevOps-инженер» в Skillbox, директор программного комитета DevOpsConf.

Содержание

  • Как создать BAT-файл
  • Команды и синтаксис
  • Как объявить переменную
  • Как комментировать строки
  • Примеры BAT-файлов
  • Как запустить BAT-файл через командную строку

BAT-файлы — это скрипты с набором команд, которые понимает командная строка Windows. Их можно использовать для автоматизации задач, которые часто повторяются или занимают у пользователя много времени. Такие скрипты хранятся в файлах с расширением .bat.

Для создания BAT-файла понадобится любой текстовый редактор, например стандартный «Блокнот». Давайте откроем его и напишем скрипт, который выведет в окне командной строки сообщение Hello, World!:

@echo off
echo Hello, World!
pause

Теперь нужно сохранить документ в формате .bat. Для этого выберем пункт Сохранить как в разделе меню Файл.

Скриншот: «Блокнот» / Skillbox Media

В появившемся окне можно ввести любое название файла, а конце надо обязательно добавить расширение .bat. Затем нажимаем Сохранить:

Скриншот: «Блокнот» / Skillbox Media

Если запустить получившийся файл, откроется командная строка с нашим сообщением:

Скриншот: «Командная строка» / Skillbox Media

Для разработки батников существует множество команд. Рассмотрим те, что встречаются чаще всего.

Команда Аргумент команды Действие
title Желаемый заголовок Устанавливает заголовок окна командной строки на желаемый
cd Путь к каталогу Переводит пользователя в каталог, указанный в пути к файлу
start Команда или путь к файлу Запускает указанный файл программы или выполнение команды в новом окне командной строки
mkdir или md Имя папки Создаёт папку с указанным именем
copy Имена файлов и путь к папке для копирования Копирует файлы в указанный каталог
xcopy Имена файлов и путь к папке для копирования Копирует каталоги и файлы, сохраняя их структуру
move Путь к файлу и к конечному каталогу Перемещает файлы из одной папки в другую
del Путь к папке Удаляет файлы внутри каталога. Не трогает папки
rd Путь к папке Удаляет папку
start Путь к файлу программы Запускает файл программы
color Обозначение цвета Меняет цвет фона и текста командной строки
echo Текст Выводит текст на экран командной строки
chcp Обозначение кодировки Указывает кодировку текста. Пригодится для корректного отображения кириллицы
pause По окончании выполнения команд оставляет окно командной строки запущенным
exit Завершает работу командной строки

Переменная — виртуальная ячейка с присвоенным именем, в которой хранятся данные. Это может быть текст, числа или выражения. К переменной можно обращаться по имени, чтобы использовать её содержимое или перезаписывать его.

В BAT-файлах переменная объявляется с помощью команды set. После команды надо указать уникальное имя переменной и присвоить ей значение:

@echo off
set example=Hi,user!
echo %example%
pause

Разберём строки скрипта:

  • @echo off — эта строка отключает отображение команд. Будут показаны только строки, которые начинаются с echo.
  • set example=Hi, user! — создаёт переменную с именем primer и записывает в неё строку Hi, user!.
  • echo %example% — выводит содержимое переменной на экран.
  • pause — эта команда не даёт окну закрыться сразу после выполнения скрипта, чтобы мы могли оценить результат.

Если запустить этот BAT-файл, то в командной строке появится содержимое переменной example:

Скриншот: «Командная строка» / Skillbox Media

Для записи в переменную значения выражения надо использовать флаг /a перед именем:

set /a example=5*10

В BAT-файлах бывает очень много строк кода. Настолько много, что в них можно заблудиться, а со временем забыть логику всего скрипта. В таких случаях лучше использовать комментарии, объясняющие код. Они не отображаются при запуске и не влияют на выполнение команд.

Для создания однострочных комментариев используют команду rem или двойное двоеточие (::):

rem текст_комментария
:: текст_комментария

Например, следующий скрипт не выведет на экран строку Следующие команды выводят текст на экран:

@echo off
rem Следующие команды выводят текст на экран
set primer=Hi, user! 
echo %primer%
pause

Для больших комментариев на несколько строк можно использовать команду goto:

goto comment
===
текст_комментария
===
:comment

Обратите внимание, что после goto следует название метки — comment, она же и закрывает комментарий в конце. На самом деле можно использовать любое название метки, главное — чтобы оно было уникальным.

Разберём примеры готовых BAT-файлов для разных задач. Их можно скопировать и использовать уже сейчас.


Допустим, необходимо время от времени создавать копию всех текстовых файлов, лежащих в каталоге Документы. Чтобы не делать это каждый раз вручную, можно создать скрипт и запускать его с рабочего стола.

Батники лучше начинать с команды @echo off, чтобы избавиться от служебных строк, которые информируют о ходе выполнении скрипта. Убрав их, мы ничего не потеряем. Если нужно будет выводить текст, написанный кириллицей, то второй строчкой BAT-файла нужно указать кодировку:

chcp 65001

При каждом запуске скрипта в папке backup на диске C: будем создавать директорию с текущей датой в названии — так будет проще искать бэкапы. Для этого используем команду md с параметром %DATE%:

md "C:/backup/%DATE%"

Теперь скопируем содержимое папки «Документ» в созданную директорию. С помощью параметра %USERNAME% можно обратиться к файлам текущего пользователя, если на компьютере их несколько:

xcopy "C:/Users/%USERNAME%/Documents" "C:/backup/%DATE%"

Для экономии места будем архивировать бэкапы с помощью 7-zip. Нужно будет предварительно скачать и установить программу по инструкции на сайте разработчика.

Далее переходим в каталог с резервными копиями с помощью команды cd и вызываем 7-zip с параметром -tzip. Появится архив бэкапа в формате .zip:

cd "C:/backup/%DATA%"
"C:/Program Files/7-Zip/7z.exe" -tzip a %DATE%.zip %DATE%

Ход выполнения скрипта можно сопровождать сообщениями командной строки, чтобы пользователь узнал, когда резервное копирование завершится. Для вывода сообщений используется команда echo.

Кроме того, текст, выводящийся на экран, можно покрасить с помощью команды color, передав ей код цвета. Эту строчку лучше добавлять в начало батника.

Весь список доступных цветов приведён в таблице:

Таблица цветов для оформления скриптов
Скриншот: «Командная строка» / Skillbox Media

Так выглядит перекрашенная командная строка Windows
Скриншот: «Командная строка» / Skillbox Media

Полный текст скрипта для резервного копирования файлов:

@echo off
chcp 65001
color 03
echo Начинается процесс резервного копирования
md "C:/backup/%DATE%"
xcopy "C:/Users/%USERNAME%/Documents" "C:/backup/%DATE%"
cd "C:/backup/%DATA%"
"C:/Program Files/7-Zip/7z.exe" -tzip a %DATE%.zip %DATE%
echo Процесс завершен
pause

Бывает, что для работы надо запустить одновременно несколько приложений — например, браузер, мессенджер, редактор кода и клиент Git. Этот процесс можно автоматизировать, чтобы все необходимые программы открывались по одному клику.

Исполняемые файлы запускаются командой start. В качестве аргумента ей надо передать путь к файлу на диске:

start "" "путь_к_исполняемому_файлу"

Так, чтобы открыть одновременно браузер Microsoft Edge, текстовый редактор WordPad и приложение «Службы», надо трижды вызвать команду start:

start "" "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
start "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"
start "" "C:\Windows\system32\services.msc"

Перед аргументом всегда добавляйте двойные кавычки («»), иначе откроются не программы, а новые экземпляры командной строки.

В Windows есть папка Temp, в которой система собирает временные файлы из браузера и приложений. Если её не очищать, то со временем её размеры могут увеличиться до десятков гигабайт.

Пользователи редко чистят папку с временными файлами. Для этого надо включить отображение скрытых папок, найти директорию на диске и вручную удалять мусор. Проще автоматизировать эту задачу с помощью простого BAT-файла, который будет очищать папку Temp по клику мыши или расписанию.

Сначала вызовем команду rd с параметрами /s и /q — это полностью удалит папку с диска. Затем создадим Temp заново с помощью mkdir:

rd /s /q C:\Users\%USERNAME%\AppData\Local\Temp\
mkdir C:\Users\%USERNAME%\AppData\Local\Temp\

Запускать BAT-файлы можно разными способами. Самый очевидный — двойной щелчок левой кнопкой мыши. Также можно делать это из командной строки или настроить автоматический запуск по расписанию.


  • Откройте окно поиска Windows. Он находится рядом с меню «Пуск».
  • Введите в строке поиска cmd и запустите инструмент «Командная строка».

Скриншот: «Командная строка» / Skillbox Media
  • В окне командной строки укажите полный путь до файла .bat и нажмите Enter.

Скриншот: «Командная строка» / Skillbox Media

Батники в Windows открываются в окне командной строки, что иногда может мешать в работе. Простой скрипт на языке VBScript позволяет запускать BAT-файлы в фоновом режиме:

  • Откройте любой текстовый редактор, например «Блокнот».
  • Вставьте в новый документ код скрипта для скрытого запуска:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "Полный_путь_до_.bat_файла" & Chr(34), 0
Set WshShell = Nothing

  • Сохраните файл, но вместо .bat укажите расширение .vbs.
  • Запустите файл, щёлкнув по нему дважды левой кнопкой мыши.

Если у вас есть повторяющиеся задачи, то можно настроить запуск BAT-файлов по расписанию. Для этого понадобится встроенный в Windows «Планировщик заданий».

1. Нажмите сочетание клавиш Win + R, в появившемся окне введите taskschd.msc и нажмите Enter.

Скриншот: Меню «Выполнить» / Skillbox Media

2. Откроется «Планировщик заданий». В правой части его окна нажмите Создать простую задачу.

Скриншот: «Планировщик заданий» / Skillbox Media

3. В «Мастере создания простой задачи» введите имя новой задачи и её описание. Затем нажмите Далее.

Скриншот: «Мастер создания простой задачи» / Skillbox Media

4. Выберите периодичность запуска. Доступны опции с привязкой к конкретному времени или запуску системы.

Скриншот: «Мастер создания простой задачи» / Skillbox Media

5. Введите время, в которое нужно запускать задачу.

Скриншот: «Мастер создания простой задачи» / Skillbox Media

6. Отметьте пункт Запустить программу.

Скриншот: «Мастер создания простой задачи» / Skillbox Media

7. Укажите путь до вашего BAT-файла и нажмите Готово.

Скриншот: «Мастер создания простой задачи» / Skillbox Media

Теперь батник будет запускаться с заданной периодичностью. К примеру, так можно настроить автоматическое удаление временных файлов при каждом запуске системы или создание резервной копии раз в неделю.

BAT-файлы — мощный инструмент для автоматизации задач на компьютерах под управлением Windows. Больше о командах можно узнать из официальной документации Microsoft, а на GitHub разработчики публикуют коллекции полезных батников.

Попробуйте себя в IT бесплатно
Вы познакомитесь с основами разработки, напишете первую программу на Python и поймёте, как быстро устроиться в IT.

Учиться бесплатно →

Key Points

PowerShell Automation Guide for IT Pros

🔹 Key PowerShell Concepts

  • Cmdlets: Built-in lightweight commands (e.g., Get-Process)
  • Pipelines: Pass data between cmdlets (|)
  • Scripts: Sequences of commands to automate tasks
  • ISE: Integrated Scripting Environment for writing/debugging scripts

🔹 Common PowerShell Automation Tasks

  • User account management
    • Automate creation, disabling, deletion, and updates in AD
  • File & folder operations
    • Automate copying, moving, deleting, and archiving files
  • CPU & system monitoring
    • Generate usage reports with Get-Counter
  • Security & port scanning
    • Use Test-NetConnection for remote port status
  • Network config
    • Set static IPs and DNS via New-NetIPAddress

🔹 Advanced PowerShell Use Cases

  • Log monitoring & alerting
    • Monitor for keywords (e.g., “ERROR”) → send alerts
  • Log analysis
    • Count errors across logs, output to CSV
  • Third-party API integration
    • Use Invoke-RestMethod to interact with APIs
  • Data manipulation
    • Merge & export datasets using Import-Csv + Export-Csv

Cybersecurity moves fast, and IT professionals constantly seek ways to improve productivity and efficiency. This guide focuses on automation using PowerShell, one of today’s most powerful and popular scripting languages. It will provide an understanding of the fundamentals, tool capabilities, and best practices for automating repetitive tasks using PowerShell.

What is PowerShell?

PowerShell is a task automation and configuration management framework developed by Microsoft. It is a scripting language and an interactive command-line shell designed to simplify system management tasks.

PowerShell is used extensively in various IT domains, including system administration, network configuration, and cybersecurity. Its benefits include automation, simplified scripting, and the ability to manage both Windows and non-Windows systems.

While PowerShell shares some similarities with other scripting languages like Python and Bash, it’s specifically designed for Windows environments. It offers seamless integration with Windows features and applications.

Foundations of using PowerShell

To master PowerShell, it is important to grasp fundamental concepts like cmdlets (pronounced “command-lets”), which are lightweight commands used in PowerShell, and pipelines, which allow data to pass between cmdlets.

A PowerShell script is a series of commands and instructions written in the PowerShell scripting language. It allows the automation of complex tasks by executing multiple commands in sequence.

Effective use of PowerShell requires familiarity with the PowerShell Integrated Scripting Environment (ISE) and a basic understanding of scripting constructs, such as variables, loops, and conditional statements. Examples of these constructs can be found in the sections that follow.

Simple PowerShell scripts for automation

PowerShell scripts are a powerful tool for automation. They can streamline repetitive tasks, reduce human error, and save valuable time and resources.

Common PowerShell tasks and their scripts

PowerShell can be used to automate a wide range of tasks. Some examples of simpler automation tasks follow, with PowerShell code provided for each and an explanation of the functions being executed by that code.

User provisioning and management

Example code:

# Create a new user

New-ADUser -Name "James Roberts" -SamAccountName "jamesroberts" -UserPrincipalName "jamesroberts at domain.com" -AccountPassword (ConvertTo-SecureString "ChangeMe123" -AsPlainText -Force)

Explanation: This script creates a new user in Active Directory with the name “James Roberts”, assigns a SAM (Security Account Manager) account name, sets the user’s principal name, and specifies the account password.

File and folder operations

Example code:

# Copy files from one folder to another

$sourceFolder = "C:source"
$destinationFolder = "D:destination"

Copy-Item -Path "$sourceFolder*" -Destination $destinationFolder -Recurse

Explanation: This script copies all files from the source folder to the destination folder, including subdirectories (recursively).

System CPU monitoring and reporting

Example code:

# Get CPU usage

$cpuUsage = Get-Counter -Counter "Processor(_Total)% Processor Time"
$cpuUsage.CounterSamples | ForEach-Object {
    Write-Host "Processor: $($_.InstanceName), Usage: $($_.CookedValue)%"
}

Explanation: This script retrieves CPU usage information for all processors and displays the usage percentage for each.

You may also be interested in our article on How to Lower CPU Usage.

Find more monitoring-related PowerShell scripts in the NinjaOne Script Hub.

Security-related tasks

Example code:

# Check open ports on a remote host

$hostname = "example.com"
$ports = 80, 443, 22
$ports | ForEach-Object {
    $port = $_
    $result = Test-NetConnection -ComputerName $hostname -Port $port
    if ($result.TcpTestSucceeded) {
        Write-Host "Port $port is open"
    } else {
        Write-Host "Port $port is closed"
    }
}

Explanation: This script tests the availability of specific ports on a remote host and reports whether each port is open or closed.

Find more security-related scripts in NinjaOne Script Hub.

Network configuration

Example code:

# Configure a network adapter with a static IP address 

$interfaceName = "Ethernet" 
$ipAddress = "192.168.1.100" 
$subnetMask = "255.255.255.0" 
$gateway = "192.168.1.1" 
$dnsServers = "8.8.8.8", "8.8.4.4" 

Set-NetIPAddress -InterfaceAlias $interfaceName -IPAddress $ipAddress -PrefixLength 24 -DefaultGateway $gateway 
Set-DnsClientServerAddress -InterfaceAlias $interfaceName -ServerAddresses $dnsServers 

Explanation: This script configures a network adapter with a static IP address, subnet mask, default gateway, and DNS server addresses.

PowerShell automation of complex tasks

As PowerShell proficiency grows, the automation of more complex tasks and scenarios becomes achievable. Some more complex PowerShell examples follow, with explanations of the functions being executed:

Continuous log monitoring and alerting

Example code:

# Monitor a log file and send an email alert on a specific event

$logFilePath = "C:logsapp.log"
$keywordToMonitor = "ERROR"
$recipientEmail = "admin at domain.com"
$smtpServer = "smtp.domain.com"
$smtpPort = 587

Get-Content -Path $logFilePath -Wait | ForEach-Object {
    if ($_ -match $keywordToMonitor) {
        Send-MailMessage -From "alerts at domain.com" -To $recipientEmail -Subject "Error Alert" -SmtpServer $smtpServer -Port $smtpPort
    }
}

Explanation: This script continuously monitors a log file for an error condition, using the occurrence of a specific keyword (“ERROR”), then sends an email alert when it detects that keyword.

Log analysis and reporting

Example code:

# Analyze log files and generate a report

$logFiles = Get-ChildItem -Path "C:logs" -Filter "*.log" -File
$results = @()

foreach ($logFile in $logFiles) {
    $logContent = Get-Content -Path $logFile.FullName
    $errorCount = ($logContent | Select-String -Pattern "ERROR").Count
    $results += [PSCustomObject]@{
        LogFileName = $logFile.Name
        ErrorCount = $errorCount
    }
}

$results | Export-Csv -Path "log_analysis.csv" -NoTypeInformation

Explanation: This script scans a directory for log files, analyzes each log file to count the occurrences of the “ERROR” keyword, and generates a CSV report with the log file names and error counts.

You might also be interested in our article on Linux Log Management: Advanced Techniques and Best Practices.

Integration with third-party APIs

Example code:

# Interact with a REST API to retrieve data

$apiUrl = "https://api.example.com/data"
$headers = @{
    "Authorization" = "Bearer YourAuthToken"
}

$response = Invoke-RestMethod -Uri $apiUrl -Headers $headers -Method Get

# Process the response data
if ($response.StatusCode -eq 200) {
    $data = $response | ConvertFrom-Json
    Write-Host "Received data from the API:"
    $data | Format-Table
} else {
    Write-Host "Failed to retrieve data from the API. Status code: $($response.StatusCode)"
}

Explanation: This script interacts with a REST API by sending an authenticated GET request, processes the API response, and displays the received data.

Complex data manipulation

Example Code:

# Transform and aggregate data from multiple sources

$data1 = Import-Csv -Path "source1.csv"
$data2 = Import-Csv -Path "source2.csv"

# Merge data from different sources
$mergedData = $data1 | ForEach-Object {
    $item1 = $_
    $matchingItem = $data2 | Where-Object { $_.ID -eq $item1.ID }
    if ($matchingItem) {
        $_ | Select-Object *, @{Name="AdditionalProperty";Expression={$matchingItem.Property}}
    } else {
        $_
    }
}

# Export the merged data

$mergedData | Export-Csv -Path "merged_data.csv" -NoTypeInformation

Explanation: This script imports data from two CSV files, merges them based on a common ID, and exports the merged data to a new CSV file.

Case studies of real-world automation tasks solved with PowerShell

To provide practical insights into the power of PowerShell, we’ll look at two real-world scenarios where PowerShell automation has been applied to solve complex tasks.

Case study #1: Active Directory user account management

Problem: A large Government organization with thousands of employees needed an efficient way to manage user accounts in Active Directory. Management included creating new accounts, disabling or deleting accounts for employees who left, and regularly updating user attributes.

Solution: PowerShell was used to automate these tasks. Scripted tasks included:

  1. Creating new user accounts: A PowerShell script was created to read user information from a CSV file and automatically create new user accounts in Active Directory with appropriate attributes like username, password, and group memberships.
  2. Disabling or deleting inactive user accounts: Another script was developed to identify and disable or delete user accounts for employees who were no longer with the company based on the last login date. This script regularly checked user activity and performed the necessary actions.
  3. User attribute updates: PowerShell scripts were scheduled to run at specific intervals to update user attributes such as job titles, department, and contact information based on data from the HR system.

Learn more about how NinjaOne can help you easily manage Active Directory users.

Case study #2: Patch management

Problem: A system administrator working with a healthcare provider needed to ensure that all servers and workstations in the organization were regularly updated with the latest security patches to protect against vulnerabilities.

Solution: PowerShell automation was implemented to streamline patch management:

  1. Automated patch deployment: PowerShell scripts were developed to connect to servers and workstations remotely and initiate the Windows Update process. These scripts scheduled updates during maintenance windows to minimize disruption.
  2. Patch status reporting: PowerShell also helped in generating reports on the patch status of each machine. It provided insights into which machines were up to date and which needed attention.
  3. Security compliance: PowerShell scripts were used to enforce security compliance policies, ensuring that all devices were running the required updates and configurations.

These examples demonstrate how PowerShell can be a powerful tool for automating routine and time-consuming tasks in real-world IT environments, leading to improved efficiency, accuracy, and security. Real-world scenarios may involve more complex automation scripts and considerations. The actual implementation can vary based on specific requirements and organizational needs.

Learn how NinjaOne can automate patch management for any endpoint.

PowerShell scripting best practices

Proficient PowerShell script writers create consistent and coherent syntax, including using meaningful variable names, adding comments for clarity, and organizing scripts logically. Adopt the following best practices for secure task automation with PowerShell:

Use PowerShell execution policies

Set PowerShell execution policies to restrict the execution of scripts to trusted sources. For example, set the execution policy to “RemoteSigned” or “AllSigned” to ensure that only signed scripts or scripts from trusted locations can run.

Use digital signatures

Digitally signing PowerShell scripts with a code-signing certificate adds an extra layer of security. It ensures that the script has not been tampered with since it was signed. PowerShell can verify the digital signature to confirm its authenticity when executing scripts.

Follow the principle of least privilege

Follow the principle of least privilege when running PowerShell scripts. Ensure that the user or service account executing the script has the minimum necessary permissions to complete the task. Avoid using highly privileged accounts whenever possible.

Store credentials securely

When dealing with credentials in scripts, use secure methods to store and retrieve them. PowerShell provides the Get-Credential cmdlet to securely store credentials as PSCredential objects. Avoid hardcoding usernames and passwords.

Use input validation

Sanitize and validate input data to prevent code injection attacks, such as SQL injection or script injection. Avoid using user input directly in script execution without proper validation.

Implement error handling

Robust error handling in scripts allows them to handle unexpected situations gracefully. Avoid displaying sensitive information in error messages that attackers could exploit.

Use secure protocols

When connecting to remote systems or web services, use secure protocols such as HTTPS or SSH. Avoid sending sensitive information over unencrypted connections.

Regularly update and patch

Keep PowerShell and any modules or dependencies up to date with the latest security patches and updates. Outdated software can be vulnerable to known exploits.

Log and audit

Implement logging and auditing mechanisms to track script execution and detect suspicious activities. PowerShell’s Start-Transcript cmdlet can be useful for this purpose.

Perform regular code reviews

Conduct regular code reviews of PowerShell scripts to identify potential security vulnerabilities. Consider using code analysis tools to automate this process.

Follow industry recommendations

Stay informed about industry-specific security recommendations and compliance requirements (e.g., PCI DSS, HIPAA, GDPR) that apply to your organization. Ensure that any scripts developed align with these standards.

Following these security practices minimizes risks associated with PowerShell scripting, and a secure and compliant IT environment is assured. Security is an ongoing process; regularly reviewing and updating scripts is essential to staying protected against evolving threats.

Automation strategy drives efficiency

In the ever-evolving landscape of cybersecurity and IT management, a well-executed PowerShell automation strategy is not just a tool; it’s a game-changer. This strategy empowers IT professionals to optimize business operations, achieve scalability, fortify their cybersecurity posture, and retain the flexibility needed to thrive in the digital age.

By following the guidance provided, IT professionals can confidently embark on their PowerShell automation journey. The power of PowerShell lies in its versatility in automating a wide range of tasks, from the simple to the complex, making it an indispensable tool for those seeking optimal performance and efficiency.

When you’re ready to take your automation strategy to the next level, consider NinjaOne’s IT automation tools to enable automated patching, software installations or remediation actions based on reaching condition thresholds, according to your defined schedule, or ad hoc. Embed automated responses into your device and group policies, always retaining the ability to override or change policies as needed.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как изменить шрифт системы windows 11
  • Как удалить все вирусы с компьютера windows 10 без антивируса
  • Asus x540s установка windows 10 с флешки
  • Как удалять программы в windows mobile
  • System requirements for windows file server