Category Archives: PowerShell

PowerShell

PowerShell – monitorowanie sprawności dysku twardego

Ciekawy skrypt autorstwa Sama Eastmana ( https://www.linkedin.com/pulse/proactive-disk-health-monitoring-powershell-sam-eastman-sjw2c ), który w połączeniu z wysyłaniem loga na maila w przypadku innego statusu niż Healty, jest bardzo ciekawym rozwiązaniem.

<##################################################################################################
Title: Get-DiskInfo

.SYNOPSIS
    Script will query each connected disk and output statistics
###################################################################################################>

# Variables
$directoryPath = "C:\temp"
$logFilePath   = "C:\temp\DiskHealthCheck.log"
$disks         = Get-PhysicalDisk

# Functions
function Get-TempDirectory {
    # Check if the directory exists
    if (-not (Test-Path -Path $directoryPath -PathType Container)) {
        # If the directory does not exist, create it
        New-Item -Path $directoryPath -ItemType Directory
        Write-Host "Directory created: $directoryPath"
    } else {
        Write-Host "Directory already exists: $directoryPath"
    }
}

function Get-DiskInformation {
    foreach ($disk in $disks) {
        # Get Disk Reliability Statistics
        $reliabilityCounters = Get-StorageReliabilityCounter -PhysicalDisk $disk
        
        $logEntry = @"
-----------------------------------------------------------------------------------------
Disk: $($disk.FriendlyName)
Operational Status: $($disk.OperationalStatus)
Temperature: $($reliabilityCounters.Temperature)°C
Wear Level: $($reliabilityCounters.Wear)
Status: $($disk.HealthStatus)
-----------------------------------------------------------------------------------------
"@

        Add-Content -Path $logFilePath -Value $logEntry
    }
}

# Body
Get-TempDirectory
Get-DiskInformation        

ESET remover – PowerShell script

Below script allows to remove ESET product from Windows 10 / 11 without system restart nor entering to Recovery  Mode.

#WMI object refreshing
net stop winmgmt /y
winmgmt /resetrepository
net start winmgmt

# retriving GUID for ESET
$eset = Get-CimInstance -ClassName Win32_Product | Where-Object { $_.Name -like "*ESET*" }

$esetVersion = $eset.name
$Win32_Product_query = "SELECT * FROM AntivirusProduct WHERE displayName = '$esetVersion'"
$SecurityCenter2_query = Get-WmiObject -Namespace "root\SecurityCenter2" -Query "SELECT * FROM AntivirusProduct WHERE displayName = 'ESET Endpoint Security'" 
$SecurityCenter2_query2 = Get-WmiObject -Namespace "root\SecurityCenter2" -Query "SELECT * FROM AntivirusProduct WHERE displayName = 'ESET Security'"

if ($eset) {
# display GUID 
$eset | Select-Object Name, IdentifyingNumber
# ESET deinstallation
$msiGuid = $eset.IdentifyingNumber
$msiexecArgs = "/x $msiGuid /quiet /norestart"
Start-Process msiexec.exe -ArgumentList $msiexecArgs -Wait
Write-Host "ESET has been successfully uninstalled."
} 
else {
Write-Host "ESET was not found on this system" -BackgroundColor Green;
}

if ($SecurityCenter2_query) {
$SecurityCenter2_query | Remove-WMIObject
Write-Host "ESET Endpoint Security record was found in the root\SecurityCenter2 namespace. The record has been deleted" -BackgroundColor Green;
}
if ($SecurityCenter2_query2) {
$SecurityCenter2_query2 | Remove-WMIObject
Write-Host "ESET Security record was found in the root\SecurityCenter2 namespace. The record has been deleted" -BackgroundColor Green;
}

#REMOVE POSSIBLE QUARANTINE FOLDERS
$quarantine_folders = @(
"C:\ProgramData\ESET\ESET NOD32 Antivirus\Quarantine",
"C:\ProgramData\ESET\ESET Internet Security\Quarantine",
"C:\User\AppData\Local\ESET\ESET Security"
"C:\Users\Default\AppData\Local\ESET"
)
foreach ($quarantine_folder in $quarantine_folders) {
if (Test-Path $quarantine_folder) {
try {
Remove-Item -Path $quarantine_folder -Recurse -Force
Write-Host "Folder: $quarantine_folder has been deleted." -ForegroundColor Green
} catch {
Write-Host "An error occurred while deleting a folder: $quarantine_folder $_" -ForegroundColor Red
}
}
else {
Write-Host "Folder $quarantine_folder not exist." -ForegroundColor Yellow
} 
}

Powershell – masowa zmiana nazw plików

Get-ChildItem -Path e:\pliki\*.txt -File | ForEach-Object {
  $currentFile = $_.Name
  $newName = $_.Name -replace "stary_fragment_nazwy", "nowy_fragment_nazwy"
  Rename-Item -path $_ -NewName $newName
  Write-Host "Renamed file $currentFile to $newName"
}

lub inaczej:

get-childitem *txt | foreach {
  rename-item $_ $_.name.replace("stary_fragment_nazwy","nowy_fragment_nazwy")
}

Więcej nt. zmiany nazw plików: https://lazyadmin.nl/powershell/rename-files/

Powershell – Wyświetlenie plików oraz folderów których ścieżka dostępu przekracza x znaków

Get-ChildItem -path e:\ -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {$_.FullName.Length -gt 250}

Wyświetlenie liczby plików / folderów których ścieżka dostępu przekracza 250 znaków:

write-host(Get-ChildItem -path e:\ -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {$_.FullName.Length -gt 250}).count

Po przełączniku -Recourse można użyć przełącznika -File lub -Directory.

Powershell – monitorowanie temperatury CPU

function Get-Temperature {
    $t = Get-WmiObject MSAcpi_ThermalZoneTemperature -Namespace "root/wmi"
    $returntemp = @()

    foreach ($temp in $t.CurrentTemperature)
    {
    $currentTempCelsius = ($temp / 10) - 273.15    
    $returntemp += $currentTempCelsius.ToString()
    }
    return $returntemp
}
Get-Temperature

Active Directory i PowerShell – operacje na grupach

Wyświetlenie obiektów należących do grupy o nazwie GroupName

Get-ADGroupMember GroupName | Format-Table name

Wyświetlenie wszystkich grup, do których należy użytkownik o nazwie UserName

Get-ADPrincipalGroupMembership UserName | Format-Table name

Wyświetlenie użytkowników należących do grupy zabezpieczeń o nazwie SecureGroup.

Get-ADUser -filter 'memberOf -recursivematch "CN=SecureGroup, OU=IT, DC=domena, DC=local"' | Format-Table name

Dodanie użytkowników OU do grupy zabezpieczeń.

Get-ADUser -SearchBase ‘OU=nazwaOU,DC=test,DC=local’ -Filter * | ForEach-Object {Add-ADGroupMember -Identity ‘NazwaGrupyZabezpieczen’ -Members $_ }