Private/Wissen/X_Technology/X31_Windows.ps1

<#
 
# Windows-Administration
 
Windows-Administration
 
- **Hashtags** Windows Battery Akku Smb NetAdapter Share Proxy Netzwerk Administration Administrator Counter Monitoring Audit Registry PSProvider Software Product Compare
- **Version** 2019.09.20
 
#>


# ! PowerShell 7 - Das neue Cmdlet Clear-RecycleBin leert den Papierkorb:
Clear-RecycleBin -Force

#region Prozessverwaltung

Get-Process
Stop-Process
Start-Process
Wait-Process
Debug-Process

#endregion

#region Systemdienste

Get-Service
Start-Service
Stop-Service
Restart-Service
Resume-Service
Suspend-Service
Set-Service
New-Service

#endregion

#region Windows Ereignisanzeige

Get-Command -Noun 'WinEvent' -Module 'Microsoft.PowerShell.Diagnostics'

#endregion

#region Lokale Benutzer und Gruppen

Get-Command -Module 'Microsoft.PowerShell.LocalAccounts'

Get-LocalUser
Disable-LocalUser
Enable-LocalUser
Remove-LocalUser
Rename-LocalUser
Set-LocalUser
New-LocalUser

Get-LocalGroup
Set-LocalGroup
Remove-LocalGroup
Rename-LocalGroup
New-LocalGroup

Get-LocalGroupMember
Add-LocalGroupMember
Remove-LocalGroupMember

#endregion

#region Registry

# Windows Registry

# ? Information bzgl. PSProvider und -Laufwerke
Get-PSProvider -PSProvider Registry
Get-PSDrive -PSProvider Registry

# ? Nativer Registry-Pfad verwenden
Get-ChildItem -Path Registry::HKEY_CURRENT_USER\Software\Microsoft\

# ? Ein Laufwerk erstellen für den Schlüssel HKEY_CURRENT_CONFIG
New-PSDrive -Name 'HKCC' -Root 'HKEY_CURRENT_CONFIG' -PSProvider Registry

# ? In den LAufwerken wechseln
Set-Location -Path HKCC:\System\CurrentControlSet
Set-Location -Path HKCU:\

# ? Schlüssel 'Abc' erstellen
New-Item -Path 'HKCU:\Software' -Name 'Abc' -ItemType 'Key'

# ? Default-Wert für den Schlüssel 'Abc' setzen
Set-ItemProperty -Path 'HKCU:\Software\Abc' -Name '(default)' -Value 'Der Standard-Wert' -Type 'String'

# ? Eine NEUE Eigenschaft für den Schlüssel "Abc" erstellen
New-ItemProperty -Path 'HKCU:\Software\Abc' -Name 'Heute'  -Value (Get-Date -Format 'yyyy-MM-dd') -PropertyType 'String' -Force
New-ItemProperty -Path 'HKCU:\Software\Abc' -Name 'Anzahl' -Value 112          -PropertyType 'DWord'  -Force | Out-Null
# ! Mögliche Werte für PropertyType sind: String, ExpandString, Binary, DWord, MultiString, QWord, Unknown

# ? Eine VORHANDENE Eigenschaft ändern
Set-ItemProperty -Path 'HKCU:\Software\Abc' -Name 'Anzahl' -Value 113 -Type 'QWord'

# ? Den Schlüssel 'Abc' lesen
Get-Item -Path 'HKCU:\Software\Abc'

# ? Den Schlüssel 'Abc' finden
Get-ChildItem -Path 'HKCU:\SOFTWARE' | Where-Object 'PSChildName' -eq 'abc'

# ? Den Default-Wert des Schlüssels 'Abc' lesen:
Get-ItemPropertyValue -Path 'HKCU:\Software\Abc' -Name '(default)'

# ? Den Wert von Heute des Schlüssels 'Abc' lesen:
Get-ItemProperty -Path 'HKCU:\Software\Abc' -Name 'Heute'
Get-ItemProperty -Path 'HKCU:\Software\Abc' | Select-Object -ExpandProperty 'Heute'
Get-ItemPropertyValue -Path 'HKCU:\Software\Abc' -Name 'Heute'

# ? Überprüfen ob der Schlüssel 'Abc' exzisiert
Test-Path -Path 'HKCU:\Software\Abc'

# ? Die Eigenschaft 'Heute' löschen:
Remove-ItemProperty -Path 'HKCU:\Software\Abc' -Name 'Heute'

# ? Den Default-Wert des Schlüssels 'Abc' leeren:
Set-ItemProperty -Path 'HKCU:\Software\Abc' -Name '(default)' -Value $null

# ? Den Schlüssel 'Abc' mit allen Eigenschaften und Unterschlüssel löschen
Remove-Item -Path 'HKCU:\Software\Abc' -Recurse -Force

# ? REZEPT: Installierte Software auflisten
$uninstallPath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKCU:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
$uninstallPath | Get-ItemProperty  | Where-Object -Property DisplayName |  Select-Object -Property DisplayName, DisplayVersion, Publisher, UninstallString

# ? „Als anderer Benutzer ausführen“ dem Windows 10 Startmenü hinzufügen
New-Item -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer' -ItemType Key -Force | New-ItemProperty -Name "ShowRunAsDifferentUserInStart" -Value 1 -PropertyType "DWORD" -Force

#region Registry vergleichen, z.b. vor- mit nach einer Installation

function Compare-HKLM {
    $HKLM1 = Get-ChildItem -Path "HKLM:\" -Recurse -ErrorAction Ignore | ForEach-Object -Process { foreach($propertyName in $_.GetValueNames()) { "{0} : {1} : {2}" -f $_.Name, $propertyName, $_.GetValue($propertyName) } }
    Read-Host "Scan erneut starten - Enter"
    $HKLM2 = Get-ChildItem -Path "HKLM:\" -Recurse -ErrorAction Ignore | ForEach-Object -Process { foreach($propertyName in $_.GetValueNames()) { "{0} : {1} : {2}" -f $_.Name, $propertyName, $_.GetValue($propertyName) } }
    Compare-Object -ReferenceObject $HKLM1 -DifferenceObject $HKLM2  | Format-Table -Wrap
}

function Compare-HKCU {
    $HKCU1 = Get-ChildItem -Path "HKCU:\" -Recurse -ErrorAction Ignore | ForEach-Object -Process {foreach($propertyName in $_.GetValueNames()) {"{0} => {1} => {2}" -f $_.GetValue($propertyName), $propertyName, $_.Name}}
    Read-Host "Scan erneut starten - Enter"
    $HKCU2 = Get-ChildItem -Path "HKCU:\" -Recurse -ErrorAction Ignore | ForEach-Object -Process {foreach($propertyName in $_.GetValueNames()) {"{0} => {1} => {2}" -f $_.GetValue($propertyName), $propertyName, $_.Name}}
    Compare-Object -ReferenceObject $HKCU1 -DifferenceObject $HKCU2  | Format-Table -Wrap
}

#endregion

#endregion

#region WMI & CIM

<#
 
# WIM&CIM
 
Windows Management Instrumentation (WMI (alt)) alias CIM (neu) nutzen
 
- **Hashtags** CIM WMI
- **Version** 2019.11.08
 
#>


# ! * CIM ist unter Windows eine der wichtigsten Schnittstellen für die Administration und Fernwartung
# ! von Workstations und Servern mittels Skriptsprachen.
# ! * Über CIM kann lesend und schreibend, lokal oder vom Netzwerk aus, auf nahezu alle Einstellungen
# ! eines Windows-Computers zugegriffen werden.

# ? Welche sinnvollen CIM-Klassen gibt es
Get-CimClass -ClassName win32_*

# ? z.Bsp. daraus konkrete Klassen
Get-CimClass -ClassName Win32_Processor
Get-CimInstance -ClassName Win32_Processor | Format-List -Property *
Get-CimInstance -ClassName Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum
Get-CimInstance -ClassName Win32_Product | Select-Object -First 1 | Format-List -Property *
Get-CimInstance -ClassName Win32_Printer

# ? CIM-Objekt analysieren
Get-CimInstance -ClassName Win32_Product | Select-Object -First 1 | Format-List -Property *

# ? WMI-Klasse Hilfe aufrufen
$wmiClassName = "win32_product"
$uri = "https://www.bing.com/search?q={0}+site:docs.microsoft.com" -f $wmiClassName
$url = (Invoke-WebRequest -Uri $uri -UseBasicParsing).Links |
  Where-Object href -like 'https://docs.microsoft.com/*' |
  Select-Object -ExpandProperty href -First 1
Start-Process -FilePath $url

# ? Eine CIM-Methode ausführen
 Get-CimInstance -Query "SELECT * FROM Win32_Process WHERE name LIKE 'notepad%'" |
  Invoke-CimMethod -MethodName GetOwner

# ? Über ein CIM-Event informiert werden
Unregister-Event -SourceIdentifier *
$action = {
    $e = $Event.SourceEventArgs.NewEvent
    "Neuer Process gestartet, ID: {0} | NAME: {1}" -f $e.ProcessId, $e.ProcessName | Write-Warning
}
Register-CimIndicationEvent -ClassName Win32_ProcessStartTrace -SourceIdentifier ProcessStarted -Action $action # ! ADMIN-Rechte
Get-EventSubscriber -SourceIdentifier ProcessStarted
Start-Process -FilePath calc
Unregister-Event -SourceIdentifier ProcessStarted

# ? REZEPT: Windows Lizenzstatus abfragen
Get-CimInstance -ClassName SoftwareLicensingService
Get-CimInstance -ClassName SoftwareLicensingProduct | Select-Object -Property Description, LicenseStatus

# ? REZEPT: Energieoptionen => Übersicht
(Get-CimInstance -Namespace root\CimV2\power -Class Win32_PowerPlan).ElementName

# ? REZEPT: Energieoptionen => Aktuell
$powerPlan = (Get-CimInstance -Namespace root\CimV2\power -Class Win32_PowerPlan -Filter 'isActive=True').ElementName
"Aktuell: $powerPlan"

# ? REZEPT: Energieoptionen => Ändern
Get-CimInstance -Namespace root\CimV2\power -Class Win32_PowerPlan -Filter 'ElementName="Ausbalanciert"' |
  Invoke-CimMethod -MethodName Activate

# ? REZEPT: Video Auflösung ermitteln
Get-CimInstance -Class Win32_VideoController | Select-Object -Property Name, CurrentHorizontalResolution, CurrentVerticalResolution, CurrentRefreshRate, DriverVersion

# ? REZEPT: Ein MSI-Paket installieren
$msi = "c:\temp\7z920-x64.msi"
$produkte = Get-CimClass -ClassName Win32_Product
"Installation läuft ...."
$ergebnis = $produkte.Install($msi)
"... Installation fertig mit dem Ergebnis {0}" -f $ergebnis.ReturnValue
Get-CimInstance -ClassName Win32_Product | Where-Object -Property Name -like -Value "*7-zip*" | Get-Member
# ReturnValue siehe http://msdn.microsoft.com/en-us/library/aa390890(v=vs.85).aspx


<# TODO ÜBUNG CIM A
    ! VERTIEFUNG: CIM
    ? Erzeugen Sie eine verwertbare Übersicht der installierten Produkte
    ? mit folgenden Informationen: Name, InstallDate, InstallAgeInDays
      TIPPS: Get-Command, Get-Help, Get-Member; Select-Object => Hilfe (Optional)
             Get-CimInstance -ClassName Win32_Product => Obligatorisch
             Select-Object; @{Label="" ; Expression={} }; PSCustomObject => Testing bzw. Praktisch (Optional)
    * LÖSUNG: 76492d1116743f0423413b16050a5345MgB8AE8ANgBQADYARgBiAEUATwArADEARwBmAFUARwB6AE4ATQB1AC8AcQBBAFEAPQA9AHwAOAA1AGIAYQA3ADcAOQA2ADcAOQAwADUAYQAyAGMAOQBjADQAMAA3ADUANgBmADcAZgAxAGYAZgA0ADcAZQBlADMAYQBhAGEAZABlADIAYQAxADUAMgBmADYAYQBhAGYAMgA4AGIAMQBmAGMAZQAxADMAZgA0ADEAYwAyAGIAZgA0AGIAMgA5ADgAMAAyADEAYQAxADIANwAwAGYAYgBlAGUAOQBiADQANAA5AGMANQAyAGYANABjADUAMgBhADQANwBkAGEAYwBiAGEANgA5AGQAYQAwADAAYwA2ADkAMQBhADUAMgBhAGUAOABhAGUAYQAzADIANwA1AGQAZABiADUAZQA4ADAANQBiAGIAYwBjAGEAZAAzADEAZQA0ADQAZgAyAGYAMgAzAGEAYgAzADEAOQAyAGUAYQBiADEAMwAzADcAMgBmAGUAOQBjAGUAZAA0ADIAMwAxADgAOAA1AGUAYwA0AGQANwA3ADgAZAA0ADIAMAA0ADcAMAA1ADAAYgA3ADUANQBmADMANAAwADMAOQBlAGMAZAA5AGYAOQBiAGQAYwBiADYAYwBlADUAMABlAGYAMgBkADEANQA3ADMAMQAyADEAZAAzAGEAZQAzADMAOAA2ADgAMgAzADgAZAAxAGQAZABhAGQAMgA3ADQAMAAwADEAYQAwADIANAA2AGMAMwBkADAAYwBjAGIAMABhADMANwBjADkANQAyADUAMgAzAGQAMgA5AGEANQAyADkAOQAzADMAMwAyADYAMAAwAGIAYgA2AGMANwA2ADcAMQA3AGIAYwBhADQAZAA3ADEANwAzADkANQA0ADYANwA5ADUAOQA3AGQAYgAwADAAZQAxADYAYgBhADYAZABjAGIAMQAzADcAZAA5ADcAZQBmADcAMABlADgAOQA2ADcAMgBhAGIAYQAxADIAZABhAGQAMAA0ADkAZABkADMAMQA3AGIAYgAxADIAMgA2ADMAZAA2AGIAZQAzADMANABlAGQANQA3AGQAMAA4ADcAOAAwADkAOABiADQAMQAyADgAOABhADcANQBiADgANgBjAGEAYgAyADYAYQA2AGQANgA0AGIAZAAxADIAYwBhADkAZgBmADcAZABhAGQAZgAyAGUAYgAyADAANABjAGYAMwA4ADYANgAyAGMAZABmAGUAMQAzAGIAOQAwADEAOABkADcAZQBjAGIAYgA1ADMAMQAwAGUANQA3ADcAYwA4ADAAZQA1AGUANAA4ADAAZgAzADAAYwAyADgAMgA2ADEAYwBlADIAMgBkADkANgAyADIANgAzAGIAZAA2ADAAYgAyADEANwA3ADEAZAA5ADYAYgA1AGYAZAAyAGUAYwA3AGUAMABhADUAOAAzAGQAOQA0ADgAMQBhADIAZQBhADIAZAA2AGYAYgAwADAANgBiAGIAMwBlADEAZAAwAGEAYwBlADEANgBmAGEANwAxADMANAAzADYAOAA2ADEAZABkADAAYQAzAGUAOQA5ADIAOABjAGYAZABjADgAMQA3ADkAMAA3AGIAMgA1ADMAZAA3ADMAYgAxADQAYgBiAGMANQBkADAAZQA0ADEAMwBhAGIAYgA1AGMANwBhADYAOAAyADkAMgA0ADkAOABhADcANQA4ADcANQAwADkANQBkADQAYwBjAGQANwA2ADgAMgBkAGEANQBmADMAYgA4ADYANAA1AGIAMwA3AGQAOQBlADMAMwA0ADUANQAxADgAZQA3AGEAOQBkAGQAZABmADEAYwBhADIAYwAwADMAZABjAGYAMgBiADEAMABkADEAZQBmADcANwA0AGQAMABjAGEAOAA4AGUAMAA4ADQANwA4AGYAYwA4ADEAZQAwADYANgBmADkAZgA1ADgAZgBiADYANgA0AGEAYwA2ADQAOAA3ADIAMwA3AGIAZABjADcAYQA2AGEANQA0ADYAOAAxAGQAMQAzAGUAYgBhAGQAZABkADQANQA0AGYAOQBiADUAZQBkADMAMwA0AGMAOAA2AGIAZgAxAGEANgAxADMANwBhADgAYwA1ADMAYgA4AGEAZgAwAGQAMgBhADMAOQBjAGEAMgA0ADUAMwBhAGEANAA1ADcANQA3ADYANwA5ADUAMgAzADMANwA5ADcAYQBmADIANQBjAGEAZgBkADgAYwBjADkANAA2ADUANgA3AGIANQAwADUANQBjAGEANgA0AGUAYgBhADYANgA1AGYANAAyADYAMABmAGIAYwBmAGIANwAxADcAYgAwADQAMwA2ADkAYwA2AGQAMQBjADQANQBlADIANwBlADUAZgA4AGQAYwA2AGEAYwBhADMANgA3ADgAMQA1ADEANAAwAGYAYgA2ADUAMQA0ADgAOAA3ADkAZAA4AGUAZQA2ADEAZAAxAGMAMwA2ADYANAAzADYAYgA5ADEAOQAzADcAZAAxAGUAMABmADQAZQA5ADgAYwBjAGEAYQA1ADAAZgBkADgAYwA5AGIANgBiAGQAMwA5ADYAOAA0ADIAMgBkADMAZgA0ADQAZAAyADcAMQA1ADUAOQA1AGEAOQA2ADUAZAA4AGUAMAA0ADAANQBmADUAYwAxAGIAMQBiADQAMQBjADcAYwA4AGYANgAxAGQAOQBhADQAYwA1ADEANwA2AGQAZgBiADQAMQBkADIANQAxADEAMwA0ADAAYgA1AGYAYgBkADMAZQAwADAAYQAwADAANwBkADMAMAAzADQAZgBmADYAZABiADkANQA1AGQAOQA1ADYAMwA3ADcAYgBiADQAMQA1ADQANgBiADEAYwBjAGUANwA2ADcANQA5ADUAZQAwAGYAMABmAGUANABjAGMAYQBhADIANABhADEAYgAxAGEANgA1ADYAZABjADkAOQA3ADgAOQA0AGEANAAyADgAMAA1ADIAMQBkADAANgBiAGQAMAA2ADgANQBlADkANQBiADgAMAA3ADUAMgA3ADMANAAxADgANAAzADcAMAA0ADgAMAAzAGYAMAA1ADkANwBkADUAMwAwADYANQBjADkAOQAzADgAYgBiADEAMQAyADMAMwBlADcAOAAyADQAYQA0ADkANQA0AGIANQBhADgAOQBkADUAYQA5ADMAMwBmAGUAOAAyAGYAMwBiAGIANwA0ADMAOQBkAGUAYQBhADQAYQBjAGIAOABkADEAYQAxADUAYwA0AGMAZgBkAGYAYgA4ADgAMQA3AGEANQA5ADAANwBiAGYAMgA4AGEAOQAxADAAYQBhADMAMgAxADQAOQA3ADIAYgAxADUAMAAzADEANgAwAGQAZgBjADgAYQA0AGUAMgAzAGIANgAzADMAYQAzADkANgBlAGYANwAzADEAMQBhADIAYgAxADEAMgA1ADEAOABkAGQAOABmAGEANgBkADMAYQBkAGQANwA2AGMANgBkAGQAZAA3ADQANABlADkANQA4AGQAZQBjADcAMQA4AGQAOAAwADAAMAAyADEAYQA3ADgAZQBmADQAOQBmADAANAA0ADgAOQA0AGYAMwA3AGQAOAA1ADAAZAA4ADAAMAA0ADkANQA2ADEAYgA4ADMAMABlADgAMwA5ADAAZAA2AGYAMAA5AGMAZAA2AGEANwA4ADMAZABjAGMAYgBiADEAZQA2ADcAMQA4AGYAYgA2ADMAYgA1AGMAOQAwADcAZABhAGUAOABjAGYAZAAyADQAYQAyADAAMgA2ADQAYwA0ADYAMABkAGYAZQBhADEAMgBkADEAYQBlADAAOQAzADIAYgA1ADUAMwBmAGMANgA0ADQAMwBhADYAMQBiAGMANQBiADIAMwBhADUAYwBlAGQAMAAxADQAZQAyADQAZABlAGQAYQAxADUANwBkAGEAZQBlADUAMwAxADMANAAwADQAZABjAGIAZAA5AGUAZQA2AGMAMAA4ADYAYwAwADkAYwAyADQAMwA4ADAANQBjAGYAZQA5AGEAZgAzADgANQBmADAANQBhAGMAYwBjADEAOABkAGEANwAwADcAMQBlAGIAMAA0AGIAYQAyADUAMwBkADgAMwA4ADEAOAAwAGEAMABlAGIAZQAxADcAMwAyAGQAYwBhADkA
#>


#endregion

#region COM

# Das Component Object Model ist eine von Microsoft entwickelte Technik
# zur Interprozesskommunikation unter Windows. COM-Komponenten können sowohl in Form
# von Laufzeitmodulen (DLLs) als auch als ausführbare Programme umgesetzt sein.
# COM soll eine leichte Wiederverwendung von bereits geschriebenem Programmcode ermöglichen,
# zum Teil auch über Betriebssystemgrenzen hinweg. COM-Komponenten können unabhängig
# von der Programmiersprache eingesetzt werden.
# Das Component Object Model wurde von Microsoft 1992 mit der grafischen Benutzeroberfläche Windows 3.1 eingeführt.

Get-CimInstance -ClassName 'Win32_COMClass' | Measure-Object # Davon können COM-Objekte erzeugt werden

$excel = New-Object -ComObject 'Excel.Application'
$excel # s. Excel - VB for Application

# ! PowerShell 7 - Anzeige von Methoden-Signaturen von COM-Objekten:
$excel = New-Object -ComObject "Excel.Application"
# TODO Methode ohne Klammern d.h. unvollständig ausführen um so weitere Details zu erhalten:
$excel.Save

#endregion

#region Control-Panel's anzeigen

Get-ControlPanelItem | Sort-Object -Property Name
Get-ControlPanelItem -Name "Windows To Go" | Show-ControlPanelItem

#endregion

#region God-Mode-Verwaltung aktivieren

New-Item -Path ([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)) -Name "GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}" -ItemType "Directory" -Force

#endregion

#region BitLocker

Get-Command -Module 'BitLocker'

#endregion

#region Windows Defender

Get-Command -Module 'Defender'

#endregion

#region Akku- / Batterie Bericht erzeugen

Get-Command powercfg

PowerCfg.exe /BatteryReport
Start-Process "$env:USERPROFILE\Battery-Report.html"

#endregion

#region Hardwareverwaltung

# TODO - Siehe PowerShell Gallery u.a. Hersteller

Get-CimClass -ClassName 'Win32_*'

#endregion

#region Softwareverwaltung

Get-CimClass -ClassName 'Win32_Product'

#endregion

#region Dateisystem

<#
 
# Dateisystem
 
Arbeiten mit Ordner & Dateien (PSProvider FileSystem)
 
- **Hashtags** FileSystem IO ACL OneDrive Tmp FreeSpace Hash SpecialFolder OneDrive
- **Version** 2020.03.02
 
#>


# TODO Weiterführende und Nachschlage-Informationen
Get-Help -Name "about_Locations"   -ShowWindow
Get-Help -Name "about_Path_Syntax" -ShowWindow
Get-Help -Name "about_Providers"   -ShowWindow
Get-Command -Noun "Item", "ItemProperty", "ItemPropertyValue", "Acl", "Path" -Module "Microsoft.PowerShell.*"

# ! PowerShell 7 - Ein neues PS-Laufwerk um benutzerbezogene temporäre Dateien abzulegen:
Get-PSDrive -Name 'Temp'
Get-ChildItem -Path 'Temp:\'

#region Grundlegende Dateioperationen

New-Item -Path "c:\Temp\CommonFileOperations" -ItemType "Directory" -Force | Set-Location
New-Item -Path "." -Name "Target" -ItemType "Directory" -Force
New-Item -Path ".\NeueDatei.txt" -ItemType "File"
Copy-Item -Path ".\NeueDatei.txt" -Destination ".\Target\NewFile.txt" -Force
Rename-Item -Path ".\Target\NewFile.txt" -NewName "THE_NEW_FILE.TXT" -Force
Move-Item -Path ".\Target\THE_NEW_FILE.TXT" -Destination "." -Force
Set-Location -Path ".."
Remove-Item -Path ".\CommonFileOperations" -Recurse -Force

#endregion

#region ACL

# ? ACL Informationen eines Objektes anzeigen:
Get-Acl -Path "C:\Windows" | Format-List -Property "*"

# ? Vererbung aktivieren / deaktivieren:
$aclObjekt = Get-Acl -Path "C:\Temp"
$aclObjekt.SetAccessRuleProtection($true, $false)
# 1. Parameter: [bool]isProtected => true, wenn die diesem ObjectSecurity-Objekt zugeordneten Zugriffsregeln vor Vererbung geschützt werden sollen, false, wenn Vererbung zugelassen werden soll.
# 2. Parameter: [bool]preserveInheritance => true, wenn geerbte Zugriffsregeln beibehalten werden sollen, false, wenn geerbte Zugriffsregeln entfernt werden sollen. Dieser Parameter wird ignoriert, wenn isProtected den Wert false aufweist.

# ? ACL auf ein anderes Objekte übetragen
Set-Acl -AclObject $aclObjekt -Path c:\OrdnerB

# ! ... Umfassende /aufwendige Möglichkeiten ergeben sich mit dem .NET. ...
# ! ... oder Sie schauen Sich das Module NtfsSecurity aus der PowerShallGallery einmal an:

Install-Module -Name "NTFSSecurity" -SkipPublisherCheck -Scope "CurrentUser" -Force -PassThru -Verbose
Get-command -Module "NTFSSecurity"
Get-NTFSAccess -Path "C:\Temp"

#endregion

#region Auf allen FileSystem-Laufwerken suchen

Get-PSDrive -PSProvider FileSystem | Select-Object -ExpandProperty Root | Get-ChildItem -Force -File -ErrorAction Ignore

#endregion

#region Zusätzliche Informationen zu einer Datei anzeigen

Get-ChildItem -Path c:\temp -File | Select-Object -Property Name, Length, @{Label="Owner"; Expression={ $_ | Get-Acl | Select-Object -ExpandProperty Owner }}

#endregion

#region Belegter / Freier Speicher der Festplatten anzeigen

Get-PSDrive -PSProvider FileSystem

#endregion

#region Hash einer Datei berechnen, vergleichen bzw. doppelte finden

Get-FileHash -Path "C:\Windows\explorer.exe"

$filesA = Get-ChildItem -Path "C:\Program Files (x86)\WindowsPowerShell\Modules\Pester" -File -Recurse -Force | Get-FileHash -Algorithm SHA512
$filesB = Get-ChildItem -Path "C:\Program Files\WindowsPowerShell\Modules\Pester"       -File -Recurse -Force | Get-FileHash -Algorithm SHA512
Compare-Object -ReferenceObject $filesA -DifferenceObject $filesB -Property "Hash" -IncludeEqual -ExcludeDifferent -PassThru

#endregion

#region Dateien- / Ordner auf Veränderung überwachen

$fsw = New-Object -TypeName "System.IO.FileSystemWatcher"
$fsw.Path   = "C:\Temp"
$fsw.Filter = "*.txt"
$action = {
    "Dateiänderung: {0} {1}" -f $eventArgs.FullPath, $eventArgs.ChangeType | Write-Warning
}
$fsw | Get-Member -MemberType Event
Register-ObjectEvent -InputObject $fsw -EventName "Created" -Action $action -SourceIdentifier "FileSystemWatcher_Create"
Register-ObjectEvent -InputObject $fsw -EventName "Changed" -Action $action -SourceIdentifier "FileSystemWatcher_Changed"
Register-ObjectEvent -InputObject $fsw -EventName "Renamed" -Action $action -SourceIdentifier "FileSystemWatcher_Renamed"
Register-ObjectEvent -InputObject $fsw -EventName "Deleted" -Action $action -SourceIdentifier "FileSystemWatcher_Deleted"
Register-ObjectEvent -InputObject $fsw -EventName "Error"   -Action $action -SourceIdentifier "FileSystemWatcher_Error"
Get-EventSubscriber

New-Item -Path "C:\Temp\test1.txt" -Force
"Hallo Würzburg!" | Add-Content -Path "C:\Temp\test1.txt"
Rename-Item -Path "C:\Temp\test1.txt" -NewName "Test_New_Name.txt"
Remove-Item -Path "C:\Temp\Test_New_Name.txt" -Force

Unregister-Event -SourceIdentifier "FileSystemWatcher_Create"  -Force
Unregister-Event -SourceIdentifier "FileSystemWatcher_Changed" -Force
Unregister-Event -SourceIdentifier "FileSystemWatcher_Renamed" -Force
Unregister-Event -SourceIdentifier "FileSystemWatcher_Deleted" -Force
Unregister-Event -SourceIdentifier "FileSystemWatcher_Error"   -Force

#endregion

#region Netzwerk-Freigabe erstellen

New-SmbShare -Name "Download" -Path "$env:USERPROFILE\Downloads"
Remove-SmbShare -Name "Download" -Confirm:$false

#endregion

#region Temporäre Dateien / Ordner

$env:TEMP
[System.IO.Path]::GetTempPath()

$tmpFile = New-TemporaryFile
$tmpFile
$tmpFile | Remove-Item

[System.IO.Path]::GetRandomFileName()

[System.IO.Path]::GetTempFileName()

#endregion

#region Den tatsächlich Ort von Spezial-Ordner lokalisieren

[Enum]::GetNames([System.Environment+SpecialFolder])
[Environment]::GetFolderPath([System.Environment+SpecialFolder]::DesktopDirectory)

Join-Path -Path $env:USERPROFILE -ChildPath "Desktop"

$env:ALLUSERSPROFILE
$env:APPDATA
$env:CommonProgramFiles
$env:HomeDrive
$env:LocalAppData
$env:OneDrive
$env:Path
$env:ProgramData
$env:ProgramFiles
${env:ProgramFiles(x86)}
$env:ProgramW6432
$env:PSModulePath
$env:SystemRoot
$env:TMP
$env:USERPROFILE
$env:WinDir

#endregion

#endregion

#region Monitoring

#region Counter

Get-Command Get-Counter -Syntax
Get-Counter
Get-Counter -ListSet * | Select-Object CounterSetName
Get-Counter -ListSet Prozessor | Select-Object -ExpandProperty Counter
Get-Counter -Counter '\Prozessor(_total)\Prozessorzeit (%)'

#endregion

# A PowerShell Network Monitor (Performance Counter)

$counters = "\netzwerkschnittstelle(*ethernet*)\bytes gesendet/s", "\netzwerkschnittstelle(*ethernet*)\empfangene bytes/s", "\netzwerkschnittstelle(*ethernet*)\gesamtanzahl bytes/s"
Get-Counter -Counter $counters -MaxSamples 30 -SampleInterval 1 | ForEach-Object {
    $network = $_.countersamples[0].InstanceName
    $computername = [regex]::Match($_.CounterSamples[0].path, "(?<=\\\\)\w+").Value.toUpper()
    $time = $_.timestamp
    $total = $_.countersamples.where( {$_.path -match "gesamtanzahl"})
    $totalKbps = $total.cookedValue*0.008
    if ($totalKbps -gt 100) {
        $totalPct = 100
    }
    else {
        $totalPct = $totalKbps
    }
    $sent = $_.countersamples.where( {$_.path -match "gesendet"})
    $sentKbps = $sent.cookedValue*0.008
    if ($sentKbps -gt 100) {
        $sentPct = 100
    }
    else {
        $sentPct = $sentKbps
    }
    $rcvd = $_.countersamples.where( {$_.path -match "empfangene"})
    $rcvdKbps = $rcvd.cookedValue*0.008
    if ($rcvdKbps -gt 100) {
        $rcvdPct = 100
    }
    else {
        $rcvdPct = $rcvdKbps
    }
    Write-Progress -Activity "[$time] $computername : $network" -status "Total Kbps $totalKbps" -id 1 -PercentComplete $totalpct
    Write-Progress -Activity " " -status "Send Kbps $sentKbps" -id 2 -PercentComplete $sentpct
    Write-Progress -Activity " " -status "Received Kbs $rcvdKbps" -id 3 -PercentComplete $rcvdpct

}

#region Windows System Assessment Tool

winsat formal # ! 1. Test ausführen
Get-CimInstance -ClassName Win32_WinSAT # ! 2. Ergebnis anzeigen

#endregion

#endregion

#region Netzwerk

#region Netzwerk-Freigabe erstellen

New-SmbShare -Name Data -Path C:\Windows
Remove-SmbShare -Name Data -Confirm:$false

#endregion

#region Netzwerk-Adapter neustarten

Get-NetAdapter -IncludeHidden                       # Übersicht
Restart-NetAdapter -Name WLAN                       # Einen
Restart-NetAdapter -Name * -PassThru -IncludeHidden # Alle

#endregion

#region Proxy-Server

$webProxy = New-Object System.Net.WebProxy("proxy.gewKoelnAg.de:8080", $true)
$webProxy.Credentials = New-Object Net.NetworkCredential("user","password","domain.local")
$netCred = New-Object System.Net.NetworkCredentials("user", "pwd", "domain");
$webClient = New-Object System.Net.WebClient
#$webClient.Proxy = $webProxy
$webClient.Credentials=$netCred
$page = $webClient.DownloadString("http://intranet/content/de/index.php")
$page
#$webClient.Upload.....

#endregion

#region Windows Firewall

Get-Command -Module 'NetSecurity'

Get-NetFirewallRule | Select-Object -property * -First 1
Get-NetFirewallRule -Enabled False | Select-Object -property * -First 1

Set-NetFirewallRule -Name 'SNMPTRAP-In-UDP' -Enabled False -PassThru

Get-NetFirewallRule -Enabled False | Out-GridView -OutputMode Multiple | Set-NetFirewallRule -Enabled True -PassThru

New-NetFirewallRule # s. Hilfe

#endregion

#endregion

#region Apps über die Windows PowerShell entfernen

# ! Hinweis: Mit dem folgendem Befehl können Sie alle vorinstallierten Apps wieder installieren.
Get-AppxPackage | ForEach-Object { Add-AppxPackage -register "$($_.InstallLocation)\appxmanifest.xml" -DisableDevelopmentMod }

# ! Hinweis: Eine Liste mit allen installierten Apps und den entsprechenden Programmnamen finden Sie unter Einstellungen > Apps > Standard-Apps > Standard-Apps

# TODO 3D Builder
Get-AppxPackage *3dbuilder* | Remove-AppxPackage -AllUsers

# TODO Alarm und Uhr
Get-AppxPackage *windowsalarms* | Remove-AppxPackage -AllUsers

# TODO Asphalt 8: Airborne
Get-AppxPackage *Asphalt8Airborne* | Remove-AppxPackage -AllUsers

# TODO Begleiter für / Ihr Smartphone
Get-AppxPackage *windowsphone* | Remove-AppxPackage -AllUsers
Get-AppxPackage *YourPhone* | Remove-AppxPackage -AllUsers

# TODO Candy Crush Saga
Get-AppxPackage *CandyCrushSaga* | Remove-AppxPackage -AllUsers

# TODO Drawboard PDF
Get-AppxPackage *DrawboardPDF* | Remove-AppxPackage -AllUsers

# TODO Erste Schritte
Get-AppxPackage *getstarted* | Remove-AppxPackage -AllUsers

# TODO Facebook
Get-AppxPackage *Facebook* | Remove-AppxPackage -AllUsers

# TODO Feedback Hub
Get-AppxPackage *feedback* | Remove-AppxPackage -AllUsers

# TODO Filme & TV
Get-AppxPackage *zunevideo* | Remove-AppxPackage -AllUsers

# TODO Finanzen
Get-AppxPackage *bingfinance* | Remove-AppxPackage -AllUsers

# TODO Fotos
Get-AppxPackage *photos* | Remove-AppxPackage -AllUsers

# TODO Groove-Musik
Get-AppxPackage *zunemusic* | Remove-AppxPackage -AllUsers

# TODO Kalender & Mail
Get-AppxPackage *communicationsapps* | Remove-AppxPackage -AllUsers

# TODO Kamera
Get-AppxPackage *windowscamera* | Remove-AppxPackage -AllUsers

# TODO Karten
Get-AppxPackage *windowsmaps* | Remove-AppxPackage -AllUsers

# TODO Kontakte
Get-AppxPackage *people* | Remove-AppxPackage -AllUsers

# TODO Microsoft Solitaire Collection
Get-AppxPackage *solitairecollection* | Remove-AppxPackage -AllUsers

# TODO Nachrichten
Get-AppxPackage *bingnews* | Remove-AppxPackage -AllUsers

# TODO Nachrichten & Skype
Get-AppxPackage *messaging* | Remove-AppxPackage -AllUsers

# TODO Office holen
Get-AppxPackage *officehub* | Remove-AppxPackage -AllUsers

# TODO OneNote
Get-AppxPackage *onenote* | Remove-AppxPackage -AllUsers

# TODO Paint 3D
Get-AppxPackage *mspaint* | Remove-AppxPackage -AllUsers

# TODO Rechner
Get-AppxPackage *windowscalculator* | Remove-AppxPackage -AllUsers

# TODO Skype
Get-AppxPackage *skypeapp* | Remove-AppxPackage -AllUsers

# TODO Sport
Get-AppxPackage *bingsports* | Remove-AppxPackage -AllUsers

# TODO Sprachrekorder
Get-AppxPackage *soundrecorder* | Remove-AppxPackage -AllUsers

# TODO Windows DVD Player
Get-AppxPackage *dvd* | Remove-AppxPackage -AllUsers

# TODO XBox Identity Provider
Get-AppxPackage *xboxIdentityprovider* | Remove-AppxPackage -AllUsers

# TODO Xbox
Get-AppxPackage *xbox* | Remove-AppxPackage -AllUsers

# TODO Wallet
Get-AppxPackage Microsoft.Wallet | Remove-AppxPackage -AllUsers

# TODO MSPaint
Get-AppxPackage Microsoft.MSPaint | Remove-AppxPackage -AllUsers

# TODO ZuneVideo
Get-AppxPackage Microsoft.ZuneVideo | Remove-AppxPackage -AllUsers

# TODO MixedReality
Get-AppxPackage Microsoft.MixedReality.Portal | Remove-AppxPackage -AllUsers

#endregion

#region 🗃️ Alternate Data Stream (ADS) Bzgl. Unblock-File

# READ https://superuser.com/questions/1342990/how-can-i-make-windows-think-a-file-came-from-another-computer?noredirect=1&lq=1
# READ https://docs.microsoft.com/de-de/archive/blogs/askcore/alternate-data-streams-in-ntfs

Set-Location -Path C:\temp
Compress-Archive -Path C:\WINDOWS\explorer.exe -DestinationPath .\exp.zip

Set-Content -Path .\exp.zip -Stream Zone.Identifier -Value '[ZoneTransfer]', 'ZoneId=3' # ! Siehe Windows Explorer / Datei Eigenschaften

# 0 = "Local machine"
# 1 = "Local intranet"
# 2 = "Trusted sites"
# 3 = "Internet"
# 4 = "Restricted sites"

Set-Content -Path .\exp.zip -Stream ZweiterEintrag -Value 'Das ist der 2. Eintrag in den ADS!'
"Das ist der 3. Stream" | Set-Content -Path .\exp.zip:DritterStream

Get-Item -Path .\exp.zip -Stream * | Select-Object -Property Stream, Length

Get-Content -Path .\exp.zip -Stream DritterStream
Get-Content -Path .\exp.zip -Stream Zone.Identifier
Get-Item .\exp.zip:DritterStream | Get-Content

Unblock-File -Path .\exp.zip
Get-Item -Path .\exp.zip -Stream * | Select-Object -Property Stream, Length

Remove-Item -Path .\exp.zip -Stream ZweiterEintrag
Get-Item -Path .\exp.zip -Stream * | Select-Object -Property Stream, Length

#endregion