Dies ist eine alte Version des Dokuments!
$command = 'Get-ACL .\test' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encodedCommand = [Convert]::ToBase64String($bytes) $encodedCommand # RwBlAHQALQBBQ0wAIAAuAFwAdABlAHMAdA== #encodedCommand #powershell.exe -eC "RwBlAHQALQBBQ0wAIAAuAFwAdABlAHMAdA=="
Get-Process | Get-Member -MemberType Properties Get-Service | Get-Member -MemberType Method Get-Process | Get-Member -MemberType Event Get-Process | Format-Table -Property Name, CPU, Memory -AutoSize Get-Service | Format-List -Property DisplayName, Status Get-Process | Select-Object Name, Id, CPU, SessionId | Where-Object { $_.SessionId -gt 4 } Get-Process | Out-GridView Get-Service | Out-GridView Get-WmiObject Win32_UserAccount | Where-Object { $_.Name -eq "administrator" } Import-Module ActiveDirectory $user = Get-ADUser -Identity "username" -Properties * $user | Format-Table Name, SamAccountName, Email, Enabled
PS C:\> Get-PackageSource Name ProviderName IsTrusted Location ---- ------------ --------- -------- Nuget API v2 NuGet False https://www.nuget.org/api/v2/ GrapeCity NuGet False https://nuget.grapecity.com/nuget Microsoft Visual Studio Offli... NuGet False C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\ PSGallery PowerShellGet False https://www.powershellgallery.com/api/v2 PS C:\> Unregister-PackageSource -Name "GrapeCity" PS C:\> Get-PackageSource Name ProviderName IsTrusted Location ---- ------------ --------- -------- Nuget API v2 NuGet False https://www.nuget.org/api/v2/ Microsoft Visual Studio Offli... NuGet False C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\ PSGallery PowerShellGet False https://www.powershellgallery.com/api/v2 PS C:\> Register-PackageSource -Name "GrapeCity" -ProviderName "NuGet" -Location "https://nuget.grapecity.com/nuget" -Trusted Name ProviderName IsTrusted Location ---- ------------ --------- -------- GrapeCity NuGet True https://nuget.grapecity.com/nuget PS C:\> Get-PackageSource Name ProviderName IsTrusted Location ---- ------------ --------- -------- Nuget API v2 NuGet False https://www.nuget.org/api/v2/ GrapeCity NuGet True https://nuget.grapecity.com/nuget Microsoft Visual Studio Offli... NuGet False C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\ PSGallery PowerShellGet False https://www.powershellgallery.com/api/v2
PS C:\> [Net.ServicePointManager]::SecurityProtocol Tls11 PS C:\> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 PS C:\> [Net.ServicePointManager]::SecurityProtocol Tls12
Install-Module -Name PSWindowsUpdate Get-WUSettings Get-WindowsUpdate -MicrosoftUpdate [-IsInstalled] (von Microsoft) Get-WindowsUpdate -IsInstalled (von managment [wsus] server) Get-WindowsUpdate -IsAssigned (von managment [wsus] server) Get-WindowsUpdate | Format-List KB, Title, Description, Size Get-WindowsUpdate -KBArticleID KB4023057, KB5034582 Get-WindowsUpdate -Category "Critical Updates" Get-WindowsUpdate -NotCategory "Drivers" Get-WindowsUpdate -Category "Critical Updates" -NotCategory "Drivers" -Download Get-WindowsUpdate -Title "Antivirus" -Install -Verbose -AcceptAll [-AutoReboot] Get-WURebootStatus Get-WUHistory -MaxDate (Get-Date).AddDays(-1)
MySQL Client DLL von https://dev.mysql.com/downloads/file/?id=526912 herunterladen und installieren.
$mysql_server = "172.21.0.13" $mysql_user = "root" $mysql_password = "Pa$$w0rd" $dbName = "testDB" [void][system.reflection.Assembly]::LoadFrom("C:\Program Files (x86)\MySQL\MySQL Connector NET 8.4\MySql.Data.dll") $Connection = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection $Connection.ConnectionString = "SERVER=$mysql_server;DATABASE=$dbName;UID=$mysql_user;PWD=$mysql_password" $Connection.Open() $sql = New-Object MySql.Data.MySqlClient.MySqlCommand $sql.Connection = $Connection $sql.CommandText = "INSERT INTO test.a (id, test) VALUES (0,""Testtext"")" # WRITE DATA $sql.ExecuteNonQuery() # Read Data $reader = $sql.ExecuteReader() while ($reader.Read()) { for ($i = 0; $i -lt $reader.FieldCount; $i++) { Write-Host "$($reader.GetName($i)): $($reader.GetValue($i))" } Write-Host "---------" # Trennlinie zwischen Datensätzen } $reader.Close() $Connection.Close()
//Verbindung mit dem Active Directory herstellen: Import-Module ActiveDirectory //Domänencontroller abrufen: Get-ADDomainController //Aktuelles Active Directory-Forest abrufen: Get-ADForest //Organisationseinheiten (OU) abrufen: Get-ADOrganizationalUnit
//Benutzerkonto erstellen: New-ADUser -SamAccountName "Username" -UserPrincipalName "username@domain.com" -Name "Full Name" -GivenName "First Name" -Surname "Last Name" -Enabled $true -PasswordNeverExpires $true -AccountPassword (ConvertTo-SecureString "Password" -AsPlainText -Force) -PassThru //Benutzerkonto deaktivieren: Disable-ADAccount -Identity "Username" //Benutzerkonto aktivieren: Enable-ADAccount -Identity "Username" //Benutzerkonto löschen: Remove-ADUser -Identity "Username" -Confirm:$false //Benutzerkonto suchen: Get-ADUser -Filter "SamAccountName -eq 'Username'" //Benutzerkontoattribute aktualisieren: Set-ADUser -Identity "Username" -Office "New Office" -Description "New Description"
false
//OU erstellen: New-ADOrganizationalUnit -Name "OUName" -Path "OU=ParentOU,DC=domain,DC=com" //OU verschieben Move-ADObject -Identity "OU=Sales,OU=Department,DC=domain,DC=com" -TargetPath "OU=Marketing,OU=Department,DC=domain,DC=com" //OU löschen: Remove-ADOrganizationalUnit -Identity "OU=OUName,OU=ParentOU,DC=domain,DC=com" -Confirm:$false
//Gruppenrichtlinie erstellen: New-GPO -Name "GPOName" //Gruppenrichtlinie verknüpfen: New-GPLink -Name "GPOName" -Target "OU=OUName,OU=ParentOU,DC=domain,DC=com" //Gruppenrichtlinie löschen: Remove-GPO -Name "GPOName" -Confirm:$false // Gruppenrichtlinien einer Gruppe Import-Module GroupPolicy $gruppenname = "GroupName" $gruppe = Get-ADGroup -Filter { Name -eq $gruppenname } $gruppenID = $gruppe.ObjectGUID $gruppenrichtlinien = Get-GPO -All | Where-Object { $_.User.DistinguishedName -contains "CN=$gruppenID" } $gruppenrichtlinien //Gruppenrichtlinien eines benutzer Import-Module GroupPolicy $benutzername = "Username" $benutzer = Get-ADUser -Filter { SamAccountName -eq $benutzername } $benutzerID = $benutzer.ObjectGUID $gruppenrichtlinien = Get-GPO -All | Where-Object { $_.User.DistinguishedName -contains "CN=$benutzerID" } $gruppenrichtlinien
Get-DhcpServerv4Scope Get-DhcpServerv4Lease -ScopeId "10.0.0.0" Import-Module DhcpServer # DHCP-Bereich Parameter $ScopeName = "TestScope" $StartRange = "192.168.1.100" $EndRange = "192.168.1.200" $SubnetMask = "255.255.255.0" # DHCP-Bereich erstellen Add-DhcpServerv4Scope -Name $ScopeName -StartRange $StartRange -EndRange $EndRange -SubnetMask $SubnetMask # Scope gateway setzen Set-DhcpServerv4OptionValue -ScopeId "192.168.1.0" -Router 192.168.1.1 -DnsDomain "zarat.local"
DNS-Zone erstellen:
Add-DnsServerPrimaryZone -Name "ZoneName" -ZoneFile "ZoneFileName.dns"
DNS-Eintrag erstellen:
Add-DnsServerResourceRecordA -Name "RecordName" -ZoneName "ZoneName" -IPv4Address "IPAddress" -CreatePtr
DNS-Eintrag löschen:
Remove-DnsServerResourceRecord -ZoneName "ZoneName" -RRType "A" -Name "RecordName" -RecordData "IPAddress" -Confirm:$false
Invoke-Command -ComputerName "dc01" -ScriptBlock { $recs = Get-DnsServerResourceRecord -ZoneName "domain.local" | Where-Object { $_.HostName -like "*" } foreach ($rec in $recs) { $output = "$($rec.HostName) $($rec.RecordClass) $($rec.RecordType)" switch ($rec.RecordType) { "A" { $output += " $($rec.RecordData.IPv4Address)" } "AAAA" { $output += " $($rec.RecordData.IPv6Address)" } "CNAME" { $output += " $($rec.RecordData.HostNameAlias)" } "MX" { $output += " $($rec.RecordData.MailExchange) Pref: $($rec.RecordData.Preference)" } "NS" { $output += " $($rec.RecordData.NameServer)" } "TXT" { $output += " $($rec.RecordData.DescriptiveText)" } "SRV" { # Extrahiere den Service und das Protokoll aus dem HostName $serviceProtocol = $rec.HostName -split '\.' $service = $serviceProtocol[0] $protocol = $serviceProtocol[1] $output += " Service: $service Protocol: $protocol Priority: $($rec.RecordData.Priority) Weight: $($rec.RecordData.Weight) Port: $($rec.RecordData.Port) Target: $($rec.RecordData.DomainName)" } "SOA" { $output += " $($rec.RecordData.PrimaryServer) AdminEmail: $($rec.RecordData.ResponsiblePerson) SerialNumber: $($rec.RecordData.SerialNumber) RefreshInterval: $($rec.RecordData.RefreshInterval) RetryDelay: $($rec.RecordData.RetryDelay) ExpireLimit: $($rec.RecordData.ExpireLimit) MinimumTTL: $($rec.RecordData.MinimumTimeToLive)" } default { $output += " Other: $($rec.RecordData)" } } Write-Output $output } }
Enter-PSSession -ComputerName "Domänencontroller" $gpo = New-GPO -Name "Meine Firewall-GPO" $rule = New-GPOSettignsObject -Cmdlet "New-NetFirewallRule" -Property @{ DisplayName = "Meine Firewall-Regel" Direction = "Inbound" LocalPort = 80 Protocol = "TCP" Action = "Allow" } Add-GPOTarget -Name $gpo.DisplayName -Setting $rule $gpo = Get-GPO -Name "Meine Firewall-GPO" Set-GPInheritance -Name $gpo.DisplayName -Target (Get-ADOrganizationalUnit -Identity "OU-Pfad") Invoke-GPUpdate -Computer "Computername" -Force
$session = New-PSSession -ComputerName "DomainController" -Credential "Domain\User" Invoke-Command -Session $session -ScriptBlock { $gpo = Get-GPO -Name "Meine Firewall-GPO" $rule = Get-NetFirewallRule -DisplayName "Meine Regel" $rule.LocalPort = 8080 Set-NetFirewallRule -InputObject $rule } Remove-PSSession -Session $session
# Replikationsverbindungen anzeigen Get-ADReplicationConnection #replication connection konfigurieren Set-ADReplicationConnection -Identity "CN=ConnectionName,CN=NTDS Settings,CN=ServerName,CN=Servers,CN=SiteName,CN=Sites,CN=Configuration,DC=Domain,DC=com" -ReplicationSchedule (New-Schedule -Daily -At "15:00") # zeitplan Set-ADReplicationSiteLink -Identity "CN=SiteLinkName,CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration,DC=Domain,DC=com" -Schedule (New-Schedule -Daily -At "10:00") # filter Set-ADReplicationAttributeMetadata -Object "CN=Object,CN=Users,DC=Domain,DC=com" -Attribute "AttributeName" -Filter (New-Object DirectoryServices.ActiveDirectory.DirectoryServerReplicationFilter -ArgumentList "FilterType")
Verwaltung einer Microsoft Exchange OnPremise Installation
Start-ExchangeManagementConsole // Postfach erstellen New-Mailbox -UserPrincipalName user@domain.com -Alias user -Name "Vorname Nachname" -OrganizationalUnit "OU=Benutzer,DC=domain,DC=com" //Berechtigungen für ein Postfach festlegen: Add-MailboxPermission -Identity user -User manager -AccessRights FullAccess,Editor,SendAs,SendOnBehalf,ReadPermission,WritePermission,DeleteItem,CreateItems,EditOwnedItems,EditAllItems,FolderVisible,FolderOwner //Verteilergruppe erstellen: New-DistributionGroup -Name "Vertriebsgruppe" -Alias "Vertrieb" -Members user1, user2, user3 //Sicherheitsgruppe erstellen: New-DistributionGroup -Name "IT-Sicherheit" -Alias "ITSecurity" -SecurityEnabled $true //Postfachdaten exportieren: New-MailboxExportRequest -Mailbox user -FilePath "\\Server\Share\user.pst" //Postfachdaten importieren: New-MailboxImportRequest -Mailbox user -FilePath "\\Server\Share\user.pst" //E-Mail-Adresse zu einem Postfach hinzufügen: Set-Mailbox -Identity user -EmailAddresses @{add="neueadresse@domain.com"} //E-Mail-Adresse von einem Postfach entfernen: Set-Mailbox -Identity user -EmailAddresses @{remove="alteadresse@domain.com"} //Exchange-Datenbanken auflisten: Get-MailboxDatabase //Exchange-Datenbankstatus überprüfen: Get-MailboxDatabaseCopyStatus //Exchange-Datenbank bereinigen: eseutil /d "C:\ExchangeDB\database.edb" //Exchange-Transportdienst neustarten: Restart-Service MSExchangeTransport //Exchange-Server neu starten: Restart-Computer -Force
//Neuen Benutzer erstellen: New-MsolUser -UserPrincipalName user@domain.com -DisplayName "Vorname Nachname" -FirstName "Vorname" -LastName "Nachname" -Password (ConvertTo-SecureString -String "Passwort" -AsPlainText -Force) -LicenseAssignment skuid //Benutzerlizenz zuweisen: Set-MsolUserLicense -UserPrincipalName user@domain.com -AddLicenses skuid //Benutzerkennwort ändern: Set-MsolUserPassword -UserPrincipalName user@domain.com -NewPassword (ConvertTo-SecureString -String "NeuesPasswort" -AsPlainText -Force) -ForceChangePassword $false
//Neue Verteilergruppe erstellen: New-DistributionGroup -Name "Vertriebsgruppe" -Alias "Vertrieb" -PrimarySmtpAddress "vertrieb@domain.com" //Neue Sicherheitsgruppe erstellen: New-DistributionGroup -Name "IT-Sicherheit" -Alias "ITSecurity" -PrimarySmtpAddress "it-security@domain.com" -Type "Security" //Benutzer zu einer Gruppe hinzufügen: Add-DistributionGroupMember -Identity "Vertriebsgruppe" -Member user1@domain.com, user2@domain.com
//Neue E-Mail-Richtlinie erstellen: New-RetentionPolicyTag -Name "1 Year Archive" -Type All -RetentionEnabled $true -RetentionAction MoveToArchive -AgeLimitForRetention "365" //Neue Transportregel erstellen: New-TransportRule -Name "Confidential Information" -SentToMemberOf "IT-Sicherheit" -ApplyHtmlDisclaimerText "Confidential" -ApplyHtmlDisclaimerFallbackAction Reject
# Exchange Online-Modul importieren Import-Module ExchangeOnlineManagement # Verbindung zu Exchange Online herstellen Connect-ExchangeOnline -UserPrincipalName admin@example.com
# Postfachdetails anzeigen Get-EXOMailbox -Identity user@example.com # Alle Postfächer abrufen Get-EXOMailbox # Postfach löschen Remove-EXOMailbox -Identity user@example.com # Postfach wiederherstellen (nur innerhalb der Wiederherstellungsfrist) Restore-EXOMailbox -Identity user@example.com # Postfach durchsuchen Search-EXOMailbox -Identity user@example.com -SearchQuery "Keyword" # Postfachexport durchführen New-EXOMailboxExportRequest -Mailbox user@example.com -FilePath "C:\Exports\user.pst" # Postfachimport durchführen New-EXOMailboxImportRequest -Mailbox user@example.com -FilePath "C:\Imports\user.pst"
false
# Postfachberechtigungen anzeigen Get-EXOMailboxPermission -Identity user@example.com # Berechtigung hinzufügen Add-EXOMailboxPermission -Identity user@example.com -User user2@example.com -AccessRights FullAccess # Berechtigung entfernen Remove-EXOMailboxPermission -Identity user@example.com -User user2@example.com # User2 darf als Mailbox1 senden Add-RecipientPermission -Identity "Mailbox1" -Trustee "User2" -AccessRights "SendAs" # User2 darf im Auftrag von Mailbox1 senden Set-Mailbox -Identity "Mailbox1" -GrantSendOnBehalfTo "User2"
AccessRights:
# Neue Migrationssitzung erstellen New-MigrationBatch -Name "Batch1" -SourceEndpoint $SourceEndpoint -TargetDeliveryDomain example.com # Migration starten Start-MigrationBatch -Identity "Batch1" # Migration überprüfen Get-MigrationBatch -Identity "Batch1" # Migration abbrechen Stop-MigrationBatch -Identity "Batch1"
# Bericht über Postfachgrößen erstellen Get-EXOMailboxStatistics | Select DisplayName,TotalItemSize,ItemCount # Bericht über aktive Verbindungen erstellen Get-EXOMailbox -ResultSize Unlimited | Get-EXOMailboxActivityReport -StartDate "2023-01-01" -EndDate "2023-01-31"
Import-Module AzureAD Connect-AzureAD Connect-AzureAD -TenantId <Tenant-ID>
Alle Benutzer anzeigen
Get-AzureADUser
Neuen Benutzer erstellen
New-AzureADUser -DisplayName "John Smith" -UserPrincipalName "john.smith@contoso.com" -PasswordProfile (New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile -Property @{"Password" = "Passw0rd!"})
Lizenz zuweisen
Set-AzureADUserLicense -ObjectId <Benutzerobjekt-ID> -AssignedLicenses @{add = "<Lizenz-SKU-ID>"}
Anzeigenamen ändern
Set-AzureADUser -ObjectId <Benutzerobjekt-ID> -DisplayName "Neuer Anzeigename"
Benutzer löschen
Remove-AzureADUser -ObjectId <Benutzerobjekt-ID>
Alle Gruppen enzeigen
Get-AzureADGroup
Gruppe erstellen
New-AzureADGroup -DisplayName "Sales Group" -MailEnabled $true -MailNickName "salesgroup" -SecurityEnabled $true
Benutzer einer Gruppe hinzufügen
Add-AzureADGroupMember -ObjectId <Gruppenobjekt-ID> -RefObjectId <Benutzerobjekt-ID>
Mitglieder anzeigen
Get-AzureADGroupMember -ObjectId <Gruppenobjekt-ID>
Gruppe löschen
Remove-AzureADGroup -ObjectId <Gruppenobjekt-ID>
Neue Anwendungsregistrierung
New-AzureADApplication -DisplayName "MyApp" -IdentifierUris "https://myapp" -HomePage "https://myapp.com"
Eine neue Serviceprinzipal basierend auf der Anwendungsregistrierung erstellen
New-AzureADServicePrincipal -AppId <Anwendungs-ID>
Berechtigungen (Rollen) für Anwendungsregistrierung festlegen
New-AzureADServiceAppRoleAssignment -ObjectId <Serviceprinzipalobjekt-ID> -Id <Rollen-ID> -PrincipalId <Serviceprinzipalobjekt-ID> -ResourceId <Anwendungsobjekt-ID>
Anwendungsregistrierung löschen
Remove-AzureADApplication -ObjectId <Anwendungsobjekt-ID>
# Eine Variable deklarieren und ihr einen Wert zuweisen $name = "John" # Den Wert der Variable ausgeben Write-Output $name $string1 = "Hello" $string2 = "World" $result = $string1 + " " + $string2
$meinArray = "Element1", "Element2", "Element3" # oder $meinArray = @("Element1", "Element2", "Element3") $meinArray[0] # Gibt das erste Element aus $meinArray[1] # Gibt das zweite Element aus $meinArray += "NeuesElement" $meinArray.Remove("Element2") $anzahlElemente = $meinArray.Count foreach ($element in $meinArray) { Write-Host $element } $sortiertesArray = $meinArray | Sort-Object $gefiltertesArray = $meinArray | Where-Object { $_ -like "Element*" } # Erstelle zwei Arrays $array1 = 1, 2, 3 $array2 = 4, 5, 6 # Erstelle ein Array von Arrays (mehrdimensionales Array) $mehrdimensionalesArray = @($array1, $array2) # Zeige die Elemente des mehrdimensionalen Arrays an $mehrdimensionalesArray[0] # Gibt das erste Array (array1) aus $mehrdimensionalesArray[1] # Gibt das zweite Array (array2) aus # Greife auf Elemente innerhalb der einzelnen Arrays zu $mehrdimensionalesArray[0][0] # Gibt das erste Element des ersten Arrays aus $mehrdimensionalesArray[1][2] # Gibt das dritte Element des zweiten Arrays aus
Datei als psm1 speichern.
function Test { Write-Output "Test" }
Import-Module .\ModuleName.psm1 Test
$obj = [PSCustomObject]@{ Name = "Max Mustermann" Alter = 30 Email = "max@example.com" } Write-Host $obj.Name # Ein Array aus Objekten $newData = @( [PSCustomObject]@{ Name = "Max Mustermann" Alter = 30 Email = "max@example.com" }, [PSCustomObject]@{ Name = "Erika Musterfrau" Alter = 25 Email = "erika@example.com" } )
# Speichern Sie das erste Argument in einer Variable $arg1 = $args[0] # Speichern Sie das zweite Argument in einer Variable $arg2 = $args[1] # Geben Sie die Argumente aus Write-Output "Argument 1: $arg1" Write-Output "Argument 2: $arg2"
# Überprüft, ob eine Zahl größer oder kleiner als 10 ist $zahl = 5 if ($zahl -gt 10) { Write-Output "Die Zahl ist größer als 10" } elseif ($zahl -lt 10) { Write-Output "Die Zahl ist kleiner als 10" } else { Write-Output "Die Zahl ist gleich 10" }
# Zählt von 1 bis 5 und gibt jeden Wert aus for ($i = 1; $i -le 5; $i++) { Write-Output $i }
# Eine Variable initialisieren $i = 1 # Die while-Schleife ausführen, solange $i kleiner oder gleich 5 ist while ($i -le 5) { Write-Output $i $i++ }
# Eine Variable initialisieren $i = 1 # Die do-while-Schleife ausführen do { Write-Output $i $i++ } while ($i -le 5)
$i = 1 while ($i -le 10) { $i++ if($i -eq 3) { continue } if($i -eq 4) { break } }
# Eine Funktion definieren, um die Summe zweier Zahlen zu berechnen function Add-Numbers { param( [int]$a, [int]$b ) $sum = $a + $b return $sum } # Die Funktion aufrufen und das Ergebnis speichern $result = Add-Numbers 5 3 # Das Ergebnis ausgeben Write-Output $result
Funktioniert in einem Script, nicht interaktiv.
class Sub { [string] $Property1 [string] $Property2 Sub([string] $p1, [string] $p2) { $this.Property1 = $p1 $this.Property2 = $p2 } Test([string] $p1) { Write-Host $p1 } } class Main { [Sub] $Property1 Main([Sub] $p1) { $this.Property1 = $p1 } } $sub = [Sub]::new("Wert1", "Wert2") $main = [Main]::new($sub) # Aufruf der Funktion $sub.Test("Hello world") # Anzeigen der Eigenschaften $Sub.Property1 $Main.Property1
# Filtert Prozesse nach dem Namen "chrome" Get-Process | Where-Object { $_.Name -eq "chrome" } # Filtert eine Liste von Zahlen und gibt nur die geraden Zahlen zurück $numbers = 1, 2, 3, 4, 5, 6 $filteredNumbers = $numbers.Where({ $_ % 2 -eq 0 }) # Zeigt nur den Prozessnamen und die ID für alle laufenden Prozesse an Get-Process | Select-Object Name, Id # Filtert Dateien im aktuellen Verzeichnis nach Dateien mit der Erweiterung ".txt" Get-ChildItem -Filter "*.txt"
Created as a windows command line tool, it is now also ported to linux by the mono project. Powershell can evaluate and execute c# and .NET code.
Die Powershell History findet man unter
C:\Users\%username%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
get-module [name] // informationen zu allen modulen oder einem bestimmten add-module hyper-v // modul laden get-commands -Module hyper-v // alle hyper-v befehle listen // list local users Get-WmiObject -Class Win32_UserAccount get-localuser net user // list local groups Get-WmiObject -Class Win32_Group get-localgroup net localgroup // list group members Get-LocalGroupMember -Group <Name> // script to show all local groups and their members $groups = Get-LocalGroup foreach ($group in $groups) { Write-Host "Gruppe: $($group.Name)" Write-Host "Mitglieder:" $members = Get-LocalGroupMember -Group $group.Name foreach ($member in $members) { Write-Host " -> $($member.Name)" } Write-Host } // filtering get-localuser [-name manuel] | select Name, Enabled get-localuser | select-object -property @{Name="Benutzername",Expression={$_.Name}}, @{Name="Active",Expression={$_.Enabled}}
//flush Get-NetFirewallRule | Remove-NetFirewallRule -Confirm:$false New-NetFirewallRule -DisplayName "Blockiere Port 443" -Direction Inbound -LocalPort 443 -Protocol TCP -Action Block Set-NetFirewallRule -DisplayName "Alter Regelname" -NewDisplayName "Neuer Regelname" Export-NetFirewallRule -DisplayName "Meine Regel" -FilePath "C:\Temp\MeineRegel.xml" Import-NetFirewallRule -FilePath "C:\Temp\MeineRegel.xml" Set-NetFirewallRule -DisplayName "Meine Regel" -LocalPort 8080 Set-NetFirewallRule -DisplayName "Meine Regel" -Protocol UDP Get-NetFirewallProfile -ComputerName "RemoteComputer" Set-NetFirewallRule -DisplayName "Meine Regel" -Priority 100 // the lower the higher priority New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 New-NetFirewallRule -DisplayName "Allow Messenger from localnet" -Direction Inbound -Program "C:\Program Files (x86)\Messenger\msmsgs.exe" -RemoteAddress LocalSubnet -Action Allow
Get-NetFirewallRule | Where-Object {$_.LocalPort -eq 80} Get-NetFirewallRule | Where-Object {$_.Protocol -eq 'TCP'} Get-NetFirewallRule | Where-Object {$_.Action -eq 'Block'} Get-NetFirewallRule | Where-Object {$_.LocalPort -eq 80 -and $_.Protocol -eq 'TCP'} Get-NetFirewallRule | Where-Object {$_.RemotePort -eq 443}
$arr = New-Object -TypeName "System.Collections.ArrayList" $arr = $local::Test() $arr.GetType() // for for($i = 0; $i -lt $arr.count; $i++) { write-host $arr[$i]; } // foreach foreach ($i in $arr){ write-host $i; } // while $i = 0; while($i -lt $arr.count) { write-host $arr[$i++]; } // do while $i=0 do{ write-host $arr[$i] $i++ } while ($i -lt $arr.count)
$arr = @(1,2,3) $arr += 4 $hashtable = @{} $hashtable.name = "Manuel" $hashtable.age = 36 $dict = New-Object System.Collections.Generic.Dictionary"[String,IPAddress]" $dict.Add("Computer 1", "192.168.0.2") $dict.Add("Computer 2", "192.168.0.3") foreach ($key in $dict.Keys) { Write-Host "Key: $key, Value: $($dict[$key])" } $dict = New-Object "system.collections.generic.dictionary[[string],[system.collections.generic.list[string]]]" $dictstr = New-Object "system.collections.generic.list[string]" $dictstr.Add("world") $dict.Add("hello", $dictstr);
get-command -Module ActiveDirectory Get-ADDomain Get-ADDomainController -filter * | select hostname, operatingsystem Get-ADFineGrainedPasswordPolicy -filter * Get-ADDefaultDomainPasswordPolicy invoke-command -ComputerName DC-Name -scriptblock {wbadmin start systemstatebackup -backupTarget:"Backup-Path" -quiet} // Backup System State!! Stay save :P Get-ADUser username -Properties * Get-ADUser username -Properties * | Select name, department, title Get-ADUser -Filter * Get-ADUser -SearchBase "OU=ADUnit Users,dc=ad,dc=domain,dc=com" -Filter * Disable-ADAccount -Identity mzarat Enable-ADAccount -Identity mzarat Search-ADAccount -LockedOut Unlock-ADAccount –Identity mzarat Move-ADObject -Identity "CN=Test,OU=ADUnit Users,DC=ad,DC=domain,DC=com" -TargetPath "OU=ADUnit Users,DC=ad,DC=domain,DC=com" Get-ADGroupMember -identity "HumanRessource" Get-ADGroup -filter * | Where-Object {$_.name -like "*myname*"}
#Reference Assemblies Add-Type -AssemblyName System.Windows.Forms # Create Form $Form = New-Object system.Windows.Forms.Form $Form.Text = "My Form" $Form.BackgroundImage = $Image $Form.BackgroundImageLayout = "Stretch" $Form.Width = 300 $Form.Height = 300 # Add Label $label = New-Object System.Windows.Forms.Label $label.Text = "What do you want to do?" $label.Location = New-Object System.Drawing.Size(1,1) $label.Size = New-Object System.Drawing.Size(275,35) $Form.Controls.Add($label) # Button Clicks $Button1Click = { Write-Host "Button 1 clicked" } # Create Buttons $Button1 = New-Object System.Windows.Forms.Button $Button1.Location = New-Object System.Drawing.Size(1,40) $Button1.Size = New-Object System.Drawing.Size(200,35) $Button1.Text = "Button1" $Button1.Add_Click($Button1Click) $Form.Controls.Add($Button1) # Display Form $Form.ShowDialog()
In der Console
$assemblies=( "System" ) $source=@" using System; namespace Module { public class Methods { public static int add(int a, int b) { return a + b; } public static int sub(int a, int b) { return a - b; } public static int mul(int a, int b) { return a * b; } public static int div(int a, int b) { return a / b; } } } "@ Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source -Language CSharp [Module.Methods]::add(2,3)
File: MyModule.cs
namespace MyModule { public class Methods { public Methods() { } public static int Sum(int a, int b) { return a + b; } public int Product(int a, int b) { return a * b; } } }
Compile
C:\Windows\Microsoft.NET\Framework\v4.0\csc.exe /target:library /out:MyModule.dll MyModule.cs
Load
[Reflection.Assembly]::LoadFile("c:\MyModule.dll") [MyModule.Methods]::Sum(2, 3)
Or
Add-Type -path test.dll $my = New-Object Module.Methods $my::add(2,3)
Get-CimInstance Win32_Process -Filter "name = 'notepad.exe'" | fl * // Process Info
#playing with strings $a = "Hallo Welt" $b = "wie geht es dir?" $c = $a + "$b $($b.Length)" $c.split(" ") # Regex possible, optioinal num of max tokens $c.substring(2,7) $c.IndexOf("W") # int $c.Replace("Welt","Mond") $c.Contains("Welt") # bool "Hallo Welt".CompareTo($a) # int "Hallo Welt".Equals($b) # bool #playing with files $f = "file.txt" $log = "Hello world" if(!(Test-Path $f)) { New-Item $f Set-Content $f $log } else { Add-Content $f $log } $i = 0 $regex = "World" foreach($line in Get-Content $f) { echo "$line $i" $i++ } if($i -gt 10) { Clear-Content $f } $f = "file.txt" [System.IO.File]::ReadLines($f) | ForEach { $_.split(" ")[0] }
get-content somefile.txt | where { $_ -match "expression"} // grep get-content somefile.txt | %{$_ -replace "expression","replace"} // sed
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://x-stream.ml/playlist.php', 'playlist.m3u8')"
replace multiple file names
get-childitem *.mp3 | foreach { rename-item $_ $_.Name.Replace("aaa", "bbb") }
Get-NetAdapter Get-NetAdapter -InterfaceIndex <n> Disable-NetAdapter -InterfaceIndex <n> Enable-NetAdapter -InterfaceIndex <n> Get-NetAdapter -InterfaceIndex <n> | Get-NetIpConfiguration (Get-NetAdapter -InterfaceIndex 10 | Get-NetIpInterface -AddressFamily ipv4).dhcp Get-NetIpAddress -InterfaceIndex <n> New-Netipaddress -InterfaceIndex <n> -IpAddress <ip-address> Remove-NetIPAddress -InterfaceIndex <n> [-IpAddress <ip-address>]
Set static IP
$IP = "10.10.10.10" $MaskBits = 24 # This means subnet mask = 255.255.255.0 $Gateway = "10.10.10.1" $Dns = "10.10.10.100" $IPType = "IPv4" # Retrieve the network adapter that you want to configure $adapter = Get-NetAdapter | ? {$_.Status -eq "up"} # Remove any existing IP, gateway from our ipv4 adapter If (($adapter | Get-NetIPConfiguration).IPv4Address.IPAddress) { $adapter | Remove-NetIPAddress -AddressFamily $IPType -Confirm:$false } If (($adapter | Get-NetIPConfiguration).Ipv4DefaultGateway) { $adapter | Remove-NetRoute -AddressFamily $IPType -Confirm:$false } # Configure the IP address and default gateway $adapter | New-NetIPAddress ` -AddressFamily $IPType ` -IPAddress $IP ` -PrefixLength $MaskBits ` -DefaultGateway $Gateway # Configure the DNS client server IP addresses $adapter | Set-DnsClientServerAddress -ServerAddresses $DNS
Set DHCP Interface
$IPType = "IPv4" $adapter = Get-NetAdapter | ? {$_.Status -eq "up"} $interface = $adapter | Get-NetIPInterface -AddressFamily $IPType If ($interface.Dhcp -eq "Disabled") { # Remove existing gateway If (($interface | Get-NetIPConfiguration).Ipv4DefaultGateway) { $interface | Remove-NetRoute -Confirm:$false } # Enable DHCP $interface | Set-NetIPInterface -DHCP Enabled # Configure the DNS Servers automatically $interface | Set-DnsClientServerAddress -ResetServerAddresses }
$global:init = $false $global:intend = 0 function Get-Tabs { param ( [int]$Count ) return "`t" * $Count } function Get-RecursiveGroups { param ([string]$GroupName,[hashtable]$VisitedGroups = @{}) if ($global:init -eq $false) { $global:init = $true $VisitedGroups = @{} } if ($VisitedGroups.ContainsKey($GroupName)) { return } $VisitedGroups[$GroupName] = $true $members = Get-ADGroupMember -Identity $GroupName foreach ($member in $members) { if ($member.objectClass -eq 'group') { #Write-Output "$(Get-Tabs -Count $global:intend)$($member.Name)" Write-Output "$("`t" * $global:intend)$($member.Name)" $global:intend++ Get-RecursiveGroups -GroupName $member.Name -VisitedGroups $VisitedGroups $global:intend-- } } } # Example # # Import-Module .\Get-RecursiveGroups.psm1 # Get-RecursiveGroups -GroupName "AKM Alle"
<# Set-MailboxAutoReplyConfiguration -Identity nadine.novak -AutoReplyState Scheduled -StartTime "10/01/2024 00:00:00 00:01:00" -EndTime "10/02/2024 00:00:00 00:01:00" -InternalMessage "Hier steht ein Text" -ExternalMessage "Hier steht ein Text" #> function Show-Form { Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing $form = New-Object Windows.Forms.Form -Property @{ StartPosition = [Windows.Forms.FormStartPosition]::CenterScreen Size = New-Object Drawing.Size(400, 600) Text = 'Abwesenheitsnotiz konfigurieren' Topmost = $true } $userLabel = New-Object Windows.Forms.Label $userLabel.Text = "User (vorname.nachname):" $userLabel.Location = New-Object Drawing.Point(10, 20) $userLabel.Width = 150 $form.Controls.Add($userLabel) $userTextBox = New-Object Windows.Forms.TextBox $userTextBox.Location = New-Object Drawing.Point(180, 20) $userTextBox.Width = 180 $form.Controls.Add($userTextBox) $messageLabel = New-Object Windows.Forms.Label $messageLabel.Text = "Nachricht:" $messageLabel.Location = New-Object Drawing.Point(10, 60) $form.Controls.Add($messageLabel) $messageTextBox = New-Object Windows.Forms.TextBox $messageTextBox.Location = New-Object Drawing.Point(180, 60) $messageTextBox.Width = 180 $messageTextBox.MultiLine = $true $form.Controls.Add($messageTextBox) $startDateLabel = New-Object Windows.Forms.Label $startDateLabel.Text = "Startdatum:" $startDateLabel.Location = New-Object Drawing.Point(10, 100) $form.Controls.Add($startDateLabel) $startDatePicker = New-Object Windows.Forms.MonthCalendar $startDatePicker.Location = New-Object Drawing.Point(180, 100) $startDatePicker.MaxSelectionCount = 1 $form.Controls.Add($startDatePicker) $startTimeLabel = New-Object Windows.Forms.Label $startTimeLabel.Text = "Startzeit (HH:mm):" $startTimeLabel.Location = New-Object Drawing.Point(10, 270) $form.Controls.Add($startTimeLabel) $startHourPicker = New-Object Windows.Forms.NumericUpDown $startHourPicker.Minimum = 0 $startHourPicker.Maximum = 23 $startHourPicker.Location = New-Object Drawing.Point(180, 270) $startHourPicker.Width = 50 $form.Controls.Add($startHourPicker) $startMinutePicker = New-Object Windows.Forms.NumericUpDown $startMinutePicker.Minimum = 0 $startMinutePicker.Maximum = 59 $startMinutePicker.Location = New-Object Drawing.Point(240, 270) $startMinutePicker.Width = 50 $form.Controls.Add($startMinutePicker) $endDateLabel = New-Object Windows.Forms.Label $endDateLabel.Text = "Enddatum:" $endDateLabel.Location = New-Object Drawing.Point(10, 310) $form.Controls.Add($endDateLabel) $endDatePicker = New-Object Windows.Forms.MonthCalendar $endDatePicker.Location = New-Object Drawing.Point(180, 310) $endDatePicker.MaxSelectionCount = 1 $form.Controls.Add($endDatePicker) $endTimeLabel = New-Object Windows.Forms.Label $endTimeLabel.Text = "Endzeit (HH:mm):" $endTimeLabel.Location = New-Object Drawing.Point(10, 480) $form.Controls.Add($endTimeLabel) $endHourPicker = New-Object Windows.Forms.NumericUpDown $endHourPicker.Minimum = 0 $endHourPicker.Maximum = 23 $endHourPicker.Location = New-Object Drawing.Point(180, 480) $endHourPicker.Width = 50 $form.Controls.Add($endHourPicker) $endMinutePicker = New-Object Windows.Forms.NumericUpDown $endMinutePicker.Minimum = 0 $endMinutePicker.Maximum = 59 $endMinutePicker.Location = New-Object Drawing.Point(240, 480) $endMinutePicker.Width = 50 $form.Controls.Add($endMinutePicker) $okButton = New-Object Windows.Forms.Button -Property @{ Location = New-Object Drawing.Point(100, 520) Size = New-Object Drawing.Size(75, 30) Text = 'OK' DialogResult = [Windows.Forms.DialogResult]::OK } $form.AcceptButton = $okButton $form.Controls.Add($okButton) $cancelButton = New-Object Windows.Forms.Button -Property @{ Location = New-Object Drawing.Point(200, 520) Size = New-Object Drawing.Size(75, 30) Text = 'Cancel' DialogResult = [Windows.Forms.DialogResult]::Cancel } $form.CancelButton = $cancelButton $form.Controls.Add($cancelButton) $result = $form.ShowDialog() if ($result -eq [Windows.Forms.DialogResult]::OK) { $user = $userTextBox.Text $message = $messageTextBox.Text $startDate = $startDatePicker.SelectionStart $formattedStartDate = $startDate.ToString("MM/dd/yyyy") # Formatiert das Datum im US-Format MM/dd/yyyy $endDate = $endDatePicker.SelectionStart $formattedEndDate = $endDate.ToString("MM/dd/yyyy") # Formatiert das Datum im US-Format MM/dd/yyyy $selectedStartHour = [int]$startHourPicker.Value $selectedStartMinute = [int]$startMinutePicker.Value $formattedStartHour = $selectedStartHour.ToString("D2") $formattedStartMinute = $selectedStartMinute.ToString("D2") $startTime = "$formattedStartHour`:$formattedStartMinute`:00" # Gibt die Zeit im Format HH:mm:00 zurück $selectedEndHour = [int]$endHourPicker.Value $selectedEndMinute = [int]$endMinutePicker.Value $formattedEndHour = $selectedEndHour.ToString("D2") $formattedEndMinute = $selectedEndMinute.ToString("D2") $endTime = "$formattedEndHour`:$formattedEndMinute`:00" # Gibt die Zeit im Format HH:mm:00 zurück return @{ User = $user Message = $message StartDate = $startDate StartTime = $startTime EndDate = $endDate EndTime = $endTime } } else { return $null } } $data = Show-Form if ($data -ne $null) { Write-Host "`n`nDer Befehl lautet: `n" Write-Host "Set-MailboxAutoReplyConfiguration -Identity $($data.User) -AutoReplyState Scheduled -StartTime `"$($data.StartDate) $($data.StartTime)`" -EndTime `"$($data.EndDate) $($data.EndTime)`" -InternalMessage `"$($data.Message)`" -ExternalMessage `"$($data.Message)`"" Write-Host "`n`n" } Pause
function Check-InstalledUpdates($Server) { $results = Invoke-Command -Computer $Server -ScriptBlock { $currentTLSVersion = [Net.ServicePointManager]::SecurityProtocol [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 if (-not (Get-PSRepository | Where-Object { $_.Name -eq "PSGallery" })) { Register-PSRepository -Default } if (-not (Get-Module -Name PSWindowsUpdate -ListAvailable)) { Install-Module PSWindowsUpdate -Force $global:Insallations += $Server } Get-WindowsUpdate -IsInstalled [Net.ServicePointManager]::SecurityProtocol = $currentTLSVersion } $results | Foreach-Object { Write-Output "$($_.KB) : $($_.Title)`n" } } function Check-AvailableUpdates($Server) { $results = Invoke-Command -Computer $Server -ScriptBlock { $currentTLSVersion = [Net.ServicePointManager]::SecurityProtocol [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 if (-not (Get-PSRepository | Where-Object { $_.Name -eq "PSGallery" })) { Register-PSRepository -Default } if (-not (Get-Module -Name PSWindowsUpdate -ListAvailable)) { Install-Module PSWindowsUpdate -Force $global:Insallations += $Server } Get-WindowsUpdate -IsAssigned [Net.ServicePointManager]::SecurityProtocol = $currentTLSVersion } $results | Foreach-Object { Write-Output "$($_.KB) : $($_.Title)`n" } } function Uninstall-ModulePSWindowsUpdate($Server) { Invoke-Command -Computer $Server -ScriptBlock { if (Get-Module -Name PSWindowsUpdate -ListAvailable) { Uninstall-Module PSWindowsUpdate -Force -ErrorAction Stop } } } $Servers = @( "server" ) foreach($Server in $Servers) { Write-Output "`n[*****] Prüfe Server $Server`n" Check-AvailableUpdates $Server Uninstall-ModulePSWindowsUpdate $Server Write-Output "`n[*****] OK`n" }
$outlook = New-Object -ComObject Outlook.Application $namespace = $outlook.GetNamespace("MAPI") $contactsFolder = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderContacts) $existingContacts = $contactsFolder.Items | Where-Object { $_.Class -eq [Microsoft.Office.Interop.Outlook.OlObjectClass]::olContact } foreach ($existingContact in $existingContacts) { $existingContact.Delete() } Write-Host "Alle Kontakte im Standard-Kontakte-Ordner wurden gelöscht." #exit $users = Get-ADUser -Filter * -Properties Mail,extensionAttribute10 | where-Object { $_.extensionAttribute10 -eq "User" -and $_.Surname -ne $null -and $_.GivenName -ne $null -and $_.Mail -ne $null } $newContacts = @() foreach($user in $users) { $newContacts += @{ Vorname = "$($user.GivenName)"; Nachname = "$($user.Surname)"; Email = "$($user.Mail)" } } foreach($newContact in $newContacts) { $contact = $contactsFolder.Items.Add([Microsoft.Office.Interop.Outlook.OlItemType]::olContactItem) $contact.FirstName = "$($newContact.Vorname)" $contact.LastName = "$($newContact.Nachname)" $contact.Email1Address = "$($newContact.Email)" $contact.Email1DisplayName = "$($newContact.Vorname) $($newContact.Nachname) - ($($newContact.Email))" #$contact.CompanyName = "My Company" #$contact.BusinessAddress = "???" #$contact.BusinessAddressStreet = "Meine Strasse" #$contact.BusinessAddressCity = "meine Stadt" #$contact.BusinessAddressPostalCode = "Meine PLZ" #$contact.JobTitle = "Mein Jobtitel" #$contact.OfficeLocation = "Mein Büro" #$contact.BusinessTelephoneNumber = "Meine Telefonnummer" $contact.Save() Write-Host "Neuer Kontakt $($newContact.Email) wurde im Standard-Kontakte-Ordner hinzugefügt." }