Liebe Leserinnen und Leser! Damit Sie nicht alle Internetadressen und Codebeispiele abtippen müssen, möchte ich Ihnen diese Datei zur Verfügung stellen. Die Internetadressen können Sie nach dem Kopieren direkt im Webbrowser öffnen, Codebeispiele in der PowerShell ausführen. Alle Beispiele finden Sie nach Kapitel sortiert in dieser Datei. So können Sie auch nach Stichworten suchen. Links finden Sie eingerückt. Mehrzeilige Codebeispiele stehen zwischen Leerzeilen. Viel Spaß bei den praktischen Übungen. KAPITEL 1 ========= https://www.jsnover.com/Docs/MonadManifesto.pdf https://github.com/psconfeu/2018/blob/master/Jeffrey%20Snover/Keynote_psconfeu_2018.pdf https://www.youtube.com/watch?v=zy4fDSdrM7M KAPITEL 2 ========= $PSVersionTable Get-Command Get-TimeZone Get-ChildItem Get-Uptime https://github.com/PowerShell/PowerShell https://docs.microsoft.com/de-de/powershell/scripting/setup/installing-powershell-core-on-linux?view=powershell-6 https://github.com/PowerShell/PowerShell/releases curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add – sudo curl -o /etc/apt/sources.list.d/microsoft.list https://packages.microsoft.com/config/ubuntu/18.04/prod.list sudo apt-get update sudo apt-get install -y powershell pwsh $PSVersionTable sudo apt-get remove powershell brew /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew update-reset brew update brew cask install powershell pwsh $PSVersionTable KAPITEL 3 ========= https://code.visualstudio.com/download https://code.visualstudio.com/docs?start=true KAPITEL 4 ========= Get-Module Get-PSReadLineOption Set-PSReadLineOption – EditMode Windows Set-PSReadLineOption – EditMode Emacs Set-PSReadLineOption – EditMode Vi Get-PSReadLineKeyHandler Get-PSreadLineKeyHandler | Format-List KAPITEL 5 ========= Get-Verb Get-Command Set-ExecutionPolicy Get-Process Get-Process –Name "p*" Get-Process –Name "pwsh" Get-Process –Name "powershell" Copy-Item –Path "C:\Docs\geheim.pdf" –Destination "K:" Get-Command –Noun "Process" Get-Command –Verb "Get" Get-Process "pwsh" Copy-Item –Path C:\Docs\geheim.pdf –Destination K: Copy-Item C:\Docs\geheim.pdf K: Get-ChildItem –Recurse Get-ChildItem –Recurse:$true Get-Uptime –Since Get-Variable Get-Variable –Name "IsWindows" Get-Variable –Name "IsWindows" –ValueOnly $IsWindows Get-Process –Name "RubberDuck" Get-Process –Name "RubberDuck" –ErrorAction "SilentlyContinue" Copy-Item -Path ".\PS6\*.*" -Destination "C:\Hilfen" –Verbose Stop-Process –Name "pwsh" –Confirm Remove-Item -Path .\liste.csv -WhatIf Stop-Process –Name "s*" –Confirm –WhatIf Get-Command –Name Get-Command Get-Command –Module Modulname Get-Module –ListAvailable Get-Help –Name Get-TimeZone Get-Help –Name Get-TimeZone –Online https://docs.microsoft.com/de-de/powershell/module/ https://aka.ms/pscore6-docs Update-Help –UICulture en-US -Force Get-Command Get-Help –Syntax Get-Help –Name Get-Process –Examples Get-Help –Name Get-Process –Full Get-Help Get-Help Get-Help –Name about_* Get-Help –Name about_CommonParameters Get-Help "process" Get-Help "Active Directory" Save-Help –UICulture en-US –DestinationPath "\\Server07\PS6-Hilfe" -Force Update-Help –UICulture en-US –SourcePath "\\Server07\PS6-Hilfe" -Force Get-Command -Verb "Get" Get-Command –Noun "process" KAPITEL 6 ========= (Get-Date).DayOfYear (Get-Date –Date "05.10.1826").DayOfWeek (Get-Process –Name "*calc*").kill() Get-Location Get-Location | Get-Member Get-Process –Name "pwsh" Get-Process –Name "pwsh" | Select-Object -Property "*" (Get-Process –Name "pwsh").StartTime Get-Command -Verb "Get" 2, 4, 6 | ForEach-Object –Process {Write-Host "Eingabe: $_ GB. Wert in MB: " ($_ * 1024)} Get-Process | foreach Stop-Process –WhatIf Get-Module -ListAvailable | ForEach-Object –Begin {Write-Host "Starte die Ausgabe:"} –Process {$_.Path} –End {"Aufgabe beendet."} Get-ChildItem -path $PSHOME | Group-Object -Property extension –NoElement Get-Process | group Product Get-Verb | Group-Object Verb Get-Service | Group-Object {$_.Status –eq "Running"} Get-Process | Group-Object {$_.Name.Substring(0,1).ToUpper()} Get-ChildItem –Path $PSHOME | Measure-Object -Property length -Minimum -Maximum –Average Get-Content -Path .\common.txt | Measure-Object -Line -Word –Character 2, 4, 6.3, 8, 10 | Measure-Object –AllStats "Toast", "4", "6.3", "8", "7" | Measure-Object –AllStats Get-Command -Verb Get | measure Get-ChildItem -Path $PSHOME -Recurse | Measure-Object -Property PSIsContainer Get-Process | Select-Object –Property ProcessName, ID Get-Process –Name "pwsh" | Select-Object –Property * Get-Process –Name "pwsh" Get-ChildItem –Path $PSHOME | select –first 10 "alpha", "beta", "beta", "alpha" | Select-Object –Unique Get-ChildItem | Sort-Object -Property Length –Descending Get-ChildItem –Path $HOME\power* | Sort-Object -Property Length Get-Process -ProcessName s* | Sort-Object -Property ProcessName, ID Get-Process | Sort-Object -Property StartTime | Select-Object -Last 5 Get-Uptime | Tee-Object -FilePath .\gesamt.txt -Append | Out-File .\momentan.txt Get-Process | Tee-Object -FilePath .\test.txt Get-Date | Tee-Object -Variable jetzt Get-Process -Name "pwsh" Get-Process | Where-Object {$_.ProcessName -EQ "pwsh"} Get-Process | Where ProcessName -EQ "pwsh" Get-Process | Where-Object {$_.Status –EQ "Running"} Get-Process | Where Status –EQ "Running" Get-ChildItem | Where-Object {$_.Length –GT 1MB} Get-ChildItem | Where Length –GT 1MB Get-ChildItem | Where-Object {$_.PSIsContainer} Get-ChildItem | Where PSIsContainer Get-Credential | Export-CliXml –Path .\geheim.xml Import-Clixml –Path .\geheim.xml $UserInfo = Import-Clixml –Path .\geheim.xml Get-Process -Name "pwsh" | Select-Object -Property ProcessName, Id,CPU, WorkingSet | Export-Csv -Path .\prozess-pwsh.csv (Get-Culture).TextInfo | Export-Csv –Path .\culture.csv –UseCulture Get-Content –Path .\culture.csv Import-Csv –Path .\culture.csv $kultur = Import-Csv –Path .\culture.csv -UseCulture Get-Date | ConvertTo-Csv Get-Process -Name "pwsh" | ConvertTo-Html ConvertTo-Html -InputObject (Get-TimeZone) Get-Command -ParameterName InputObject Get-Process | Select-Object -Property Id, ProcessName, WS, CPU, StartTime | ConvertTo-Html -Title "Aktuelle Prozesse" -Body "

Liste der Daten zu aktuell laufenden Prozessen

" -PostContent "

Das war alles. Ich helfe gern wieder...

" | Out-File .\prozesse.html Get-IUCulture | ConvertTo-Json | Out-File .\culture.json Get-Process | ConvertTo-Xml Get-Process | ConvertTo-Xml –As Stream Get-Service | Format-Table –Wrap Get-ChildItem –Path $HOME | Format-Table –GroupBy Mode Get-PSReadLineOption | Format-Table Get-Date | Format-List Get-Process pwsh | Format-List -Property * Get-Command | Format-Wide –Column 3 Get-Command | Format-Wide -GroupBy CommandType Get-Process | Out-Host Get-Process | Out-Host -Paging | Select-Object –Property ProcessName, Id Get-Process | Select-Object –Property ProcessName, Id | Out-Host -Paging Get-History | Out-Host –FilePath .\befehlsliste.txt Get-ChildItem | Out-File –FilePath .\listing.txt –NoClobber Get-Process | Out-String -Stream | Select-String "p" Get-ChildItem -Path $PSHOME –Recurse Get-ChildItem -Path $PSHOME\m* –Recurse Get-ChildItem -Path $PSHOME\m* –Recurse | Select-Object –Property Name,Length,Directory Get-ChildItem -Path $PSHOME\m* –Recurse | Select-Object –Property Name,Length,Directory | Where-Object {$_.Length -GT 100kb} Get-ChildItem -Path $PSHOME\m* –Recurse | Select-Object –Property Name,Length,Directory | Where-Object {$_.Length -GT 100kb} | Sort-Object -Property Length –Descending Get-ChildItem -Path $PSHOME\m* –Recurse | Where-Object {$_.Length -GT 100kb} | Select-Object –Property Name,Length,Directory | Sort-Object -Property Length -Descending | Export-Csv -Path .\kollegenhilfe.csv -Delimiter ";" KAPITEL 7 ========= start pwsh Get-Alias -Name gc*, sp* Get-Alias -Definition "*-Object" Get-Alias | Group Definition | Where Count -GE 2 | Sort Count –Descending Get-Command –Noun Alias New-Alias –Name html –Value ConvertTo-Html New-Alias html ConvertTo-Html New-Alias -Name "ti65" -Value C:\Windows\System32\calc.exe -Description "DER Rechner aus Schultagen" -Option ReadOnly Get-Alias ti65 | Select * (Get-Alias ti65).Description New-Alias hilfe Get-Date Set-Alias hilfe Get-Help New-Alias –Name "sudo" –Value "runas /User:administrator" New-Alias –Name "sudo" –Value "runas" sudo /User:administrator pwsh New-Alias –Name "dirsub" –Value "Get-ChildItem -Recurse" Remove-Alias gci –Force Get-Alias | Select-Object -Property Name, Options Get-Alias | Where Options -Match "ReadOnly" Export-Alias -Path .\alias-liste.csv Export-Alias -Path .\alias-liste.csv -Name g* Import-Alias -Path .\alias-liste.csv –Force Export-Alias -Path .\alias-liste.ps1 –As Script Set-Alias -Name:"history" -Value:"Get-History" -Description:"" -Option:"None" gps | ? ws -gt 25MB | sort ws -d | select –p Name,WS -f 5 Get-Process | Where-Object {$_.WorkingSet64 -GT 25MB} | Sort-Object -Property WorkingSet64 -Descending | Select-Object –Property Name, WorkingSet64 -First 5 KAPITEL 8 ========= Get-PSProvider Get-ChildItem Get-PSDrive -PSProvider FileSystem Get-PSDrive –PSProvider Alias, Variable Set-Location Alias: Set-Location –Path C: (Get-PSDrive -Name C).CurrentLocation Get-Location Set-Location HKLM: Set-Location –Path .\ Software\Microsoft\ Set-Location C: Get-Location -PSDrive HKLM Set-Location $HOME Push-Location Set-Location $PSHOME Push-Location Set-Location $env:windir\system32\ Push-Location Set-Location HKLM: Pop-Location Pop-Location Pop-Location Pop-Location Resolve-Path –Path ~, /, .. Resolve-Path –Path $PSHOME\[d-h]*.dll Test-Path –Path C:\Tools Test-Path -Path $PSHOME -PathType Container Test-Path -Path $PSHOME -PathType Leaf Test-Path –Path $HOME –NewerThan "05.12.2018" Test-Path –Path $HOME –NewerThan (Get-Date).AddDays(-14) Test-Path -Path $HOME\Documents –Exclude *.docx –PathType Leaf New-PSDrive -Name "D" -PSProvider "FileSystem" -Root "\\W10E\Tools" New-PSDrive "Team" "FileSystem" "C:\Gemeinsame Daten\" New-PSDrive -Name A7 -PSProvider Alias -Root Alias:\ Remove-PSDrive –Name Daten Get-PSDrive -PSProvider Registry | Remove-PSDrive Get-ChildItem $PSHOME\[c-ew]*.* Get-ChildItem –Path "C:\Programme\Microsoft Office 15\" Split-Path -Path $PSHOME\pwsh.exe Get-Content –Path .\process.txt Get-Content .\process.txt -TotalCount 10 Get-Content .\process.txt -Tail 10 (Get-Content .\process.txt)[5] Set-Content -Path .\notiz.txt -Value "Das ist ein neuer Text" Get-ChildItem –Path $HOME | Set-Content –Path .\listing.txt Add-Content –Path .\einkauf.txt –Value "Milch: 2 Liter" Add-Content -Path .\woche.txt -Value (Get-Content .\mittwoch.txt) Clear-Content –Path .\*.log Get-Process | Out-File .\process.txt Set-ItemProperty -Path .\process.txt -Name IsReadOnly -Value $True Clear-Content –Path .\process.txt -Force Get-Item –Path . Get-Item * (Get-Item .\schutz.xlsx).IsReadOnly Get-Item HKCU:\Software\Microsoft\Windows\CurrentVersion\Run Set-Item -Path Alias:cc -Value "Clear-Host" Set-Item –Path Env:USERNAME –Value "Nikolaus" New-Item -Path . -Name "test.txt" -ItemType "file" New-Item -Path .\test.txt -ItemType "file" New-Item .\test.txt New-Item -Path . -Name "test.txt" -ItemType "file" –Value "Erster Eintrag..." New-Item -Path $HOME\Documents -Name "Urlaub 2019" -ItemType Directory New-Item –Path "HOME\Documents\Urlaub 2019" –ItemType Directory New-Item –Path HKCU:\Software\Microsoft\ -Name TEST Copy-Item –Path ".\Messe.docx" –Destination "C:\Messeauftritt" Copy-Item –Path ".\Messe.docx" –Destination "C:\Messeauftritt\Vortrag-AD.docx" Copy-Item "C:\Daten" -Destination "D:\Backup\Daten" –Recurse Copy-Item Alias:\clear Alias:\cc Get-ChildItem -Path $PSHOME\*.txt -Recurse | Copy-Item -Destination C:\PSCore-Doku Rename-Item -Path .\Vorlage.xlsx -NewName Job-03.xlsx Rename-Item -Path .\Vorlage.xlsx -NewName E:\Job-03.xlsx Rename-Item -Path Alias:\clear –NewName cc Move-Item –Path .\Daten.xlsx –Destination c:\Neu\Daten.xlsx Move-Item –Path .\Daten.xlsx –Destination .\AD01.xlsx Move-Item –Path C:\Daten –Destination D:\Backup Move-Item C:\Daten\*.log D:\Backup Move-Item –Path HKLM:\Software\FirmaX\* –Destination HKLM:\Software\KonzernY Remove-Item .\alte-socken.txt Remove-Item * -Include alt* -Exclude *.xlsx Remove-Item -Path .\geheim.xml -Force Remove-Item –Path HKLM:\Software\WegDamit –Recurse Clear-Item Variable:\temp Clear-Item –Path HKLM:\Software\WegDamit Invoke-Item –Path .\notiz.txt Get-ItemProperty C:\Windows\ Get-ItemProperty C:\Windows\ | Select-Object –Property * Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion Set-ItemProperty -Path .\fertig.docx -Name IsReadOnly -Value $True Set-ItemProperty -Path .\process.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-14)) Set-ItemProperty HKLM:\SOFTWARE\Microsoft\PowerShellCore\ProgramsMenuShortcut\6 -Name ProgramFilesDir -Value "D:\Programme" Remove-ItemProperty HKLM:\SOFTWARE\Microsoft\PowerShellCore\ProgramsMenuShortcut\6 -Name ProgramFilesDir Set-Location HKLM:\SOFTWARE\ New-Item -Name ZumTesten Set-Location –Path .\ZumTesten New-ItemProperty -Path . -Name Firma -Value Meine New-ItemProperty -Path . -Name Kollegen -Value 1255 Copy-ItemProperty -Path HKLM:\SOFTWARE\ZumTesten -Destination HKLM:\Software\ -Name "Kollegen" Rename-ItemProperty -Path HKLM:\SOFTWARE\ZumTesten -Name "Kollegen" –NewName "TolleKollegen" Move-ItemProperty -Path HKLM:\SOFTWARE\ZumTesten -Destination HKLM:\Software\ -Name "Kollegen" Clear-ItemProperty -Path HKLM:\SOFTWARE\ZumTesten -Name "Kollegen" Remove-ItemProperty -Path HKLM:\SOFTWARE\ZumTesten -Name "Kollegen" KAPITEL 9 ========= "Dies ist ein Textbeispiel." Get-ChildItem –Path "C:\Meine Dateien" "Ihr Benutzerverzeichnis ist $HOME." 'Ihr Benutzerverzeichnis ist $HOME. ' "Das ist ein kurzer Text." 'Das ist ein kurzer Text.' "Das ist ein 'kurzer' Text." 'Das ist ein "kurzer" Text.' "Das ist ein "kurzer" Text." 'Das ist ein 'kurzer' Text.' "Das ist ein "kurzer Text." "Betriebssystem: $env:OS" 'Betriebssystem: $env:OS' "$env:OS = $env:OS" '$env:OS = $env:OS' '$env:OS = ' + "$env:OS" "Heute: " + (Get-Date) (Get-Date) + " (das ist heute)." 5 * "38" "38" * 5 5 * "38m" "17 mal 69 ergibt $(17*69)." '17 mal 69 ergibt $(17*69).' "Zeitzone: $(Get-TimeZone)." 'Zeitzone: $(Get-TimeZone).' "``" "Ich find's `"klasse`"!" "VORSICHT!`a" "`$HOME = $HOME." "100`t200`t300`n400`t500`t600`n700`t800`t900" Write-Host ` "Der Befehl erstreckt sich über mehrere Zeilen." Get-Process ` -Name "pswh" ` -FileVersionInfo "Anzahl der Nachkommastellen von `u{3C0}: `u{221E}" "Anzahl der Nachkommastellen von `u{3C0}: " + [char]0x221E "Anzahl der Nachkommastellen von " + [char]0x3C0 + ": " + [char]0x221E "GIE" + [char]0x1E9E + "EN - GIEßEN - GIE`u{1E9E}EN" @" Textteil mit Sonderzeichen zur Auswertung. "@ @' Textteil mit Sonderzeichen zur Wiedergabe wie verfasst. '@ "PowerShell" -like "hell" "PowerShell" -like "*hell" "PowerShell" -like "*rsh*" "PowerShell" -match "hell" "PowerShell" -match "rsh" "PowerShell" -match "schell" "Text" -replace "x","s" "Ukulele" -replace "u","uuuu" -replace "uuuu","-" $env:Path –split ";" "Montag,Dienstag,Mittwoch,Donnerstag,Freitag,Samstag,Sonntag" -split "," "PowerShell", "Core", "6.1" –join " " "C:","Users","AD","Desktop" -join "\" "Get-Process" &"Get-Process" &"Get-Process" –Name pwsh &"Get-Process –Name pwsh" $befehl = "notepad.exe" &$befehl &".\mein eigenes skript.ps1" "Hallo".GetType() "Hallo".GetTypeCode() (123).GetTypeCode() (37.4).GetTypeCode() (52GB).GetTypeCode() $PSHOME.GetTypeCode() $True.GetTypeCode() (Get-Date).GetTypeCode() (Get-ChildItem).GetType() $test = "Hallo" $test = 127.5 "Textschnipsel" | Get-Member $PSHOME $PSHOME.ToLower() $PSHOME.ToUpper() " 1234 5678 ".Trim() " Andreas".TrimStart() "Peter Pan ".TrimEnd() $PSHOME.TrimStart("C:") "12345678".Trim("123") "12345678".Trim("678") "12345678".Trim("456") "Ananas".Contains("a") "Ananas".Contains("anas") "Ananas".Contains("Anas") "Ananas".StartsWith("a") "Ananas".StartsWith("A") "Ananas".StartsWith("Ana") "Ananas".EndsWith("s") "Ananas".EndsWith("S") "Ananas".EndsWith("as") "PowerShell ist ein mächtiges Werkzeug.".Substring("0","10") "Ananas".Replace("anas","gebot") "test.xml".Replace(".xml",".txt") $PSHOME.Length "Test".Length "Textbeispiel".Chars "PowerShell".Chars(0) "PowerShell".Chars(7) Read-Host –Prompt "Bitte geben Sie Ihr Alter ein" Write-Host "Sie geben an, $(Read-Host -Prompt "Bitte geben Sie Ihr Alter ein") Jahre alt zu sein." $alter = Read-Host –Prompt "Bitte geben Sie Ihr Alter ein" $alter Read-Host -Prompt "Neues Kennwort" –AsSecureString $pass = Read-Host -Prompt "Neues Kennwort" –AsSecureString [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass)) $cred = Get-Credential $cred $cred = Get-Credential –Credential SomeUser Enter-PSSession –ComputerName Server05 –Credential (Get-Credential –Credential Server05\Administrator) Get-Command –ParameterName Credential "{0}, {1}, {2}" –f "Wert1", "Wert2", "Wert3" "{0} kl{0}er Rh{0}länder" -f "ein" "{0} kl{0}{1}er Rh{0}länder" -f "ein","laut" "{1}er Rh{0}länder" –f "ein","laut" "{0:c}" -f 100 https://docs.microsoft.com/de-de/dotnet/standard/base-types/formatting-types Get-ChildItem -File | ForEach-Object {"{0,-30}: {1,10} Bytes" -f $_.Name, $_.Length} "BLZ: {0: 00 000 000}" -f 17566 "{0:d4}" –f 815 "{0:n2}" –f 815 (Get-ChildItem -Path $PSHOME | Measure-Object -Property Length -Sum).Sum / 1GB "{0:N2} GB" -f ((Get-ChildItem -Path $PSHOME | Measure-Object -Property Length -Sum).Sum / 1GB) "{0:#.##}" –f 1234567890 "{0:0.00}" –f 1234567890 "{0:0.000}" –f 1234567890 "{0:0,0}" –f 1234567890 "{0:0,.}" –f 1234567890 "{0:0%}" –f 1234567890 "{0:c}" –f 1234567890 "{0:d}" –f 1234567890 "{0:d14}" –f 1234567890 "{0:e}" –f 1234567890 "{0:f}" –f 1234567890 "{0:g}" –f 1234567890 "{0:n}" –f 1234567890 "{0:n4}" –f 1234567890 "{0:x}" –f 1234567890 "{0:X}" –f 1234567890 "{0:d}" -f (Get-Date) "{0:D}" -f (Get-Date) "{0:f}" -f (Get-Date) "{0:F}" -f (Get-Date) "{0:g}" –f (Get-Date) "{0:G}" –f (Get-Date) "{0:R}" -f (Get-Date) "{0:s}" -f (Get-Date) "{0:u}" -f (Get-Date) "{0:U}" -f (Get-Date) "{0:t}" -f (Get-Date) "{0:T}" -f (Get-Date) "{0:MM}`n{0:MMM}`n{0:MMMM}" -f (Get-Date) "{0:dd}" –f (Get-Date) "{0:ddd}" –f (Get-Date) "{0:dddd}" –f (Get-Date) "{0:gg}" –f (Get-Date) "{0:hh}" –f (Get-Date) "{0:HH}" –f (Get-Date) "{0:M}" –f (Get-Date) "{0:mm}" –f (Get-Date) "{0:MM}" –f (Get-Date) "{0:MMM}" –f (Get-Date) "{0:MMMM}" –f (Get-Date) "{0:ss}" –f (Get-Date) "{0:t}" –f (Get-Date) "{0:T}" –f (Get-Date) "{0:Y}" –f (Get-Date) "{0:yy}" –f (Get-Date) "{0:yyyy}" –f (Get-Date) "{0:zz}" –f (Get-Date) "{0:zzz}" –f (Get-Date) "Jetzt: {0:M} {0:yyyy} {0:gg} [{0:t} Uhr]" -f (Get-Date) https://docs.microsoft.com/de-de/dotnet/standard/base-types/regular-expressionlanguage-quick-reference https://danielfett.de/de/tutorials/tutorial-regulare-ausdrucke/ "PowerShell Core" –match "\bCore\z" "PowerShell Core" –notmatch "\bCore\z" 1..50 | ForEach-Object {"Server-{0:d2}" -f $_} | Select-String -Pattern "\b\d4" –AllMatches Get-Help –Name about_operators | Select-String -pattern "operators?.*" -AllMatches | ForEach-Object {($_.matches).value} "PowerShell Version 5.0" -replace "\d\.","6." -replace "\.\d",".1" (Read-Host "IPv4-Adresse eingeben").Trim() -match "\A(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\z" KAPITEL 10 ========== $PROFILE.AllUsersAllHosts $PROFILE.AllUsersCurrentHost $PROFILE.CurrentUserAllHosts $PROFILE.CurrentUserCurrentHost $PROFILE Test-Path –Path $PROFILE New-Item –Path $PROFILE –ItemType File notepad $PROFILE gedit $PROFILE open -e $PROFILE $Tag = (Get-Date).DayOfYear $Jahr = (Get-Date).Year Write-Host "Hallo, $env:USERNAME!" -ForegroundColor White -BackgroundColor Blue Write-Host "Heute ist der $Tag. Tag des Jahres $Jahr." # ...und viele weitere Definitionen pwsh -NoProfile Get-Help about_pwsh Get-ExecutionPolicy Set-ExecutionPolicy –Scope CurrentUser –ExecutionPolicy RemoteSigned Set-ExecutionPolicy RemoteSigned Set-ExecutionPolicy –Scope CurrentUser RemoteSigned Set-ExecutionPolicy –Scope LocalMachine Restricted Get-PSReadLineOption Get-PSReadLineOption | Get-Member -Name *color Set-PSReadLineOption -Colors @{"Number" = "DarkYellow"; "Parameter" = "Cyan"} Set-PSReadLineOption -Colors @{"Variable" = "#FFA500"} Set-PSReadLineOption -Colors @{"Number" = "DarkYellow"; "Parameter" = "Cyan"; "Variable" = "#FFA500"} Set-PSReadLineOption -Colors @{ "Number" = "DarkYellow" "Parameter" = "Cyan" "Variable" = "#FFA500" } $Host.PrivateData.ErrorForegroundColor = "DarkBlue" $Host.PrivateData.ErrorBackgroundColor = "DarkYellow" function prompt {"PS [$(hostname)> "} function prompt {"PS [$env:COMPUTERNAME]> "} function prompt {"$(Get-Date)> "} function prompt {"PS $(Get-Date –Format HH:mm)> "; $Host.UI.RawUI.WindowTitle = "$(Get-Location) +++ Benutzer: $env:USERNAME"} $Tag = (Get-Date).DayOfYear $Jahr = (Get-Date).Year Write-Host "Hallo, $env:USERNAME!" -ForegroundColor White -BackgroundColor Blue Write-Host "Heute ist der $Tag. Tag des Jahres $Jahr." # ...und viele weitere Definitionen Set-PSReadLineOption -Colors @{ "Number" = "DarkYellow" "Parameter" = "Cyan" "Variable" = "#FFA500" } $Host.PrivateData.ErrorForegroundColor = "DarkBlue" $Host.PrivateData.ErrorBackgroundColor = "DarkYellow" KAPITEL 11 ========== $ErrorActionPreference 1..3 | Get-ChildItem –Path C:\GibtsNicht $ErrorActionPreference = "SilentlyContinue" 1..3 | Get-ChildItem –Path C:\GibtsNicht $x = 67 $x = $y = $z = 86 $x, $y, $z = 10, 20, 30 $Name = "Mond (lat. luna)" $Entfernung_Mond_km = 384400 $Name $Entfernung_Mond_km "Der $Name ist etwa $Entfernung_Mond_km km von der Erde entfernt." $a = Get-Process -Name w* | Select-Object -Property Id, Name | Sort-Object -Property ID $b = (Get-Date -Date "7.2.2007").DayOfWeek New-Variable –Name "Kennwort" –Value 123456 New-Variable –Name "NurLesen1" –Value "Wert mit Schreibschutz" –Option ReadOnly New-Variable –Name "Konstante_Pi" –Value 3.14159265 –Option Constant [System.Math]::PI [Math]::PI https://docs.microsoft.com/de-de/dotnet/api/system.math?view=netframework-4.7.2. New-Variable –Name test –Value 123 Set-Variable –Name "test" –Value "eins, zwei, drei" Set-Variable –Name "gibts_noch_nicht" –Value 438 –Option ReadOnly Get-Variable Get-ChildItem –Path Variable: Get-Variable –Name PSHOME Get-Variable –Name p* $a = 67 Clear-Variable –Name a $a Clear-Variable –Name my_*, ad_* Remove-Variable –Name a Remove-Variable –Name my_* New-Variable –Name "GoldenerSchnitt" –Value 1.618034 –Option Constant Get-Variable | Where-Object {$_.Options -match "constant"} $array1 = 27, 04, 3.44, "Teekessel", ((Get-Date).DayOfWeek) New-Variable –Name array1 –Value 27, 04, 3.44, "Teekessel", ((Get-Date).DayOfWeek) [array] $array2 $array2 = 1, 2, 3, 4, 5, 6, 7, 8, 9 $array2 = 1..9 $array2.Count $array_leer = @() $array_mit_daten = @(1, 2, 3, 4, 5, 6) $array_mit_daten = @(1, 2, 3, 4, 5, 6) $array_mit_daten += 7 $array_mit_daten += 8, 9 $array_mit_daten.Count $array_mit_daten[0] $array_mit_daten[1] $array_mit_daten[5] $array_mit_daten[-1] $array_mit_daten[0, 2, 7] $array_mit_daten[2..6] Clear-Variable $array_mit_ daten[5] = $null $team_go = @{PointGuard = "MS"; ShootingGuard = "DL"; SmallForward = "PW"; "PowerForward" = "DW"; "Center" = "DC"} $team_go $Thema = @{} $Thema["Kategorie"] = "PowerShell" $Thema.Edition = "Core" $Thema["Version"] = 6.1 $Thema.OS = "Linux" Write-Host $Thema.Kategorie $Thema.Edition "- momentan unter" $Thema.OS $a = 5 $b = "6" $a * $b $b * $a $zahl = Read-Host "Eingabe Zahl" Write-Host "Eingegebene Zahl * 10 = " ($zahl * 10) [int]$zahl = Read-Host "Eingabe Zahl" [int]$AntwortAufAlles = 42 [int] $AntwortAufAlles = 42 [int] $AntwortAufAlles = "42" [int] $AntwortAufAlles = "zweiundvierzig" $AntwortAufAlles –Is [int] $AntwortAufAlles –IsNot [int] $AntwortAufAlles –IsNot [string] [float]$a = 1.23456 [int]$b = [int]$a $zeichenkette = "31.3.2012" $datum = $zeichenkette –As [DateTime] $zeichenkette $datum $datum = [DateTime] $zeichenkette $x = 44 if ($x –eq 44) { Write-Host 'Die Variable $a besitzt den Wert 44.' } if ((Get-Date).DayOfWeek –eq 5) { Write-Host 'Ja, es ist Freitag!' } if ((Get-Date).DayOfWeek –eq 5) { Write-Host 'Ja, es ist Freitag!' } else { Write-Host 'Es ist leider nicht Freitag!' } if ((Get-Date).DayOfWeek –eq 5) { Write-Host 'Ja, es ist Freitag!' } elseif (((Get-Date).DayOfWeek –eq 6) –or ((Get-Date).DayOfWeek –eq 0)) { Write-Host 'Noch besser, es ist Wochenende!' } else { Write-Host 'In der Woche geht es zurück an die Werkbank!' } $schulnote = 2 switch ($schulnote) { 1 {'Sehr gut'} 2 {'Gut'} 3 {'Befriedigend'} 4 {'Ausreichend'} 5 {'Mangelhaft'} 6 {'Ungenügend'} default {'Die Eingabe entspricht keiner definierten Schulnote.'} } switch (11) { 11 {'Wert: 11'} 47 {'Wert: 47'} 8 {'Wert: 8'} {$_ -gt 10} {'Wert ist größer als 10'} } switch (11) { 11 {'Wert: 11'; break} 47 {'Wert: 47'; break} 8 {'Wert: 8'; break} {$_ -gt 10} {'Wert ist größer als 10'; break} } switch (1..10) { {$_ % 3} {"$_ ist nicht ohne Rest durch 3 teilbar."} default {"$_ ist ohne Rest durch 3 teilbar."} } $wert = "PowerShell Core 6.1" switch -Wildcard ($wert) { "*core*" {'"core" ist im Text enthalten.'} "power*" {'"power" steht am Anfang des Textes.'} "*6.1" {'Der Text endet mit "6.1"'} } $wert = "PowerShell Core 6.1" switch -Regex ($wert) { "\b.*?core.*?\b" {'"core" ist im Text enthalten.'} "^power" {'"power" steht am Anfang des Textes.'} "\d.\d" {'Der Text beinhaltet eine Zahl mit Dezimalpunkt.'} } $x = 2 while ($x -lt 2000) { Write-Host $x $x *= 2 } $a = 1 do { "Schleife: $a" "`tWert von `$a zu Beginn der Schleife = $a" $a++ "`tWert von `$a am Ende der Schleife = $a" } while ($a -le 3) for ($i = 1; $i -le 3; $i++) { Test-Connection -ComputerName 127.0.0.$i -Count 1 } for ($i=11; $i -le 20; $i++) { for ($a=11; $a -le 20; $a++) { "$a * $i = " + ($a * $i) } "`n" } $eigenes_array = 67, 42, "Sonnenblume", (Get-Date) ForEach ($element in $eigenes_array) { Write-Host "Aktuelles Element: $element" } $datei = Get-Content .\bsp_mit_leerzeilen.txt foreach ($zeile in $datei) { if ($zeile.Trim() -ne "") { Write-Host $zeile } } KAPITEL 12 ========== .\Skripte\my_script.ps1 "C:\Eigene Skripte\Noch ein Skript.ps1" & "C:\Eigene Skripte\Noch ein Skript.ps1" Write-Host "Infos zur aktuell laufenden PowerShell:" Write-Host "Version -`t" $PSVersionTable.PSVersion Write-Host "Plattform -`t" $PSVersionTable.OS Write-Host "Edition -`t" $PSVersionTable.PSEdition Write-Host "Infos zur aktuell laufenden PowerShell:`nVersion -`t" $PSVersionTable.PSVersion "`nPlattform -`t" $PSVersionTable.OS "`nEdition -`t" $PSVersionTable.PSEdition [DateTime]$geburt = "8.28.1749" [DateTime]$tod = "3.22.1832" $leben = $tod - $geburt $lebensjahre = if ($tod.DayOfYear -gt $geburt.DayOfYear) { $tod.Year - $geburt.Year } else { $tod.Year - $geburt.Year -1 } Write-Host "Johann Wolfgang von Goethe ist im Alter von $lebensjahre Jahren gestorben. Insgesamt hat er $($leben.Days) Tage gelebt." [int]$jahr = Read-Host "Bitte Jahreszahl zur Prüfung eingeben" if ($jahr%4 -eq 0 -and $jahr%100 -ne 0) { $schaltjahr = "ein Schaltjahr" } elseif ($jahr%100 -eq 0 -and $jahr%400 -eq 0) { $schaltjahr = "ein Schaltjahr" } else { $schaltjahr = "KEIN Schaltjahr" } Write-Host "Das Jahr $jahr ist $schaltjahr." [int]$jahr = Read-Host "Jahr (vierstellig)" if ([datetime]::IsLeapYear($jahr)) { Write-Host "$jahr ist ein Schaltjahr." } else { Write-Host "$jahr ist KEIN Schaltjahr." } $PSScriptRoot $logfile = $PSScriptRoot +"\script.log" if (-not (Test-Path ($logfile))) { New-Item -ItemType File -Path $logfile } Add-Content -Path $logfile -Value "$(Get-Date): Skript wurde gestartet." New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My ` -Subject "CN=Eigenes Zertifikat (Code Signing)" ` -KeyAlgorithm RSA -KeyLength 2048 ` -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" ` -KeyExportPolicy Exportable ` -KeyUsage DigitalSignature ` -Type CodeSigningCert $zertifikat = Get-ChildItem –Path Cert:\CurrentUser\My -CodeSigningCert Set-AuthenticodeSignature –FilePath .\Desktop\test1.ps1 –Certificate $zertifikat Get-ChildItem -Path C:\Windows | Where-Object {$_.Extension -eq ".exe"} Get-ChildItem -Path C:\Windows\*.exe Measure-Command -Expression {1..100 | foreach {Get-ChildItem -Path C:\Windows | Where-Object {$_.Extension -eq ".exe"}}} Measure-Command -Expression {1..100 | foreach {Get-ChildItem -Path C:\Windows\*.exe}} #Requires –RunAsAdministrator #Requires –Version 6 #Requires –Modules Storage #Requires –Modules @{ModuleName = "Storage"; RequiredVersion = "2.0.0.0"} $a = 1 $b = 2 $c = 3 Write-Host '$a = ' $a ', $b = ' $b ', $c = ' $c $a = 1 $global:b = 2 New-Variable -Name c -Value 3 -Scope global Write-Host '$a = ' $a ', $b = ' $b ', $c = ' $c Get-ChildItem # –Path hier fehlt noch etwas # Get-Date <# VORSICHT: Der Rechner muss an dieser Stelle zwingend den Namen "Mail05" erhalten, sonst funktioniert die folgende Programmierung nicht. #> Rename-Computer -NewName "Mail05" -DomainCredential Dom1\Admin12 -Restart <# +++++++++++++++++++++++++++++++++++++++ Berechnung Hypothekentilgung Projekt F8 Autor: Andreas Dittfurth Version: 2.1 Datum: 05.03.2019 Offen: Restschuld berechnen +++++++++++++++++++++++++++++++++++++++ #> # Der Inhalt des PowerShell-Installationsverzeichnisses # wird in der Variablen $a gespeichert. Get-ChildItem –Path $PSHOME # Nun wird die Variable $a ausgegeben $a # Das Programm ist hier zu Ende ... KAPITEL 13 ========== function Get-AD_Greeting { Write-Host "Schöne Grüße aus Göttingen!" } function Get-AD_PwshInfo { Get-Process -Name pwsh | Select-Object -Property Name, Id, Product, ProductVersion, Path, StartTime } $pwsh = Get-Process -Name pwsh Select-Object -InputObject $pwsh -Property Name, Id, Product, ProductVersion, Path, StartTime function Get-AD_LeapYear { [int]$jahr = Read-Host "Jahr (vierstellig)" if ([datetime]::IsLeapYear($jahr)) { Write-Host "$jahr ist ein Schaltjahr." } else { Write-Host "$jahr ist KEIN Schaltjahr." } } Get-ChildItem –Path Function: Get-Command –CommandType Function function Get-AD_ProcessInfo { param ($Process) Get-Process -Name $Process | Select-Object -Property Name, Id, Product, ProductVersion, Path, StartTime } function Get-AD_LeapYear ([int]$jahr) { if ([datetime]::IsLeapYear($jahr)) { Write-Host "$jahr ist ein Schaltjahr." } else { Write-Host "$jahr ist KEIN Schaltjahr." } } function Get-AD_LeapYear ([int]$jahr = (Get-Date).Year) { if ([datetime]::IsLeapYear($jahr)) { Write-Host "$jahr ist ein Schaltjahr." } else { Write-Host "$jahr ist KEIN Schaltjahr." } } function Test-AD_Switch { param ([switch] $schalter) if ($schalter) { Write-Host "EIN" } else { Write-Host "AUS" } } Test-AD_Switch –schalter function Get-AD_PosParam { $n = 1 foreach ($arg in $args) { Write-Host "Eingegebener Parameter $n = $arg" $n++ } } Get-AD_PosParam 1 2 4 "acht" 16 function GetAD_PosParam1 { if ($args[0] -Is [int]) {$ergebnis = 67 * $($args[0])} Write-Host $ergebnis } function Get-AD_Pipeline { Process {Write-Host "Empfangener Wert: $_"} } 16, "Butterbrot", 42 | Get-AD_Pipeline function Get-AD_PipelineInput { begin {Write-Host "Objekte über Pipeline (begin): $input"} end { Write-Host " Objekte über Pipeline (end): $input"} } 1, 2, 3, 4, 5 | Get-AD_PipelineInput function Test-AD_BeginProcessEnd { begin {"Heute ist {0:dddd}." -f (Get-Date)} process {Write-Host "Bearbeitung Objekt: $_"} end {"Fertig um: {0:HH:mm} Uhr." -f (Get-Date)} } 1, 2, 3 | Test-AD_BeginProcessEnd param ( [parameter(Mandatory=$True, ValueFromPipeline=$True, Position=0)] [ValidateNotNullOrEmpty()] [String] $Parameter1, [parameter(Mandatory=$True, Position=1)] [ValidateLength(3,16)] [String] $Parameter2, [parameter(Mandatory=$True)] [ValidateSet("Wert-1","Wert-2","Wert-3")] [String] $Parameter3 ) function Funktionsname { param ( $PC, [parameter(Position=1,HelpMessage="IPv4-Adresse")] $IPv4 ) Anweisungen } Funktionsname "Server01" "10.100.0.11" <# .SYNOPSIS Kurze, zusammenfassende Beschreibung .DESCRIPTION Ausführliche Beschreibung .PARAMETER Parameter-1 Beschreibung von Parameter 1. Pro angegebenem Parameter wird eine Sektion erzeugt. Die Reihenfolge der Beschreibungen ist beliebig. .PARAMETER Parameter-n Beschreibung von Parameter n .EXAMPLE Beispiel 1 mit Erläuterung .EXAMPLE Beispiel n mit Erläuterung .NOTES Weitere Hinweise und Informationen .LINK Angabe von Internetlinks und ähnlichen Cmdlets #> function Get-AD_Files { <# .SYNOPSIS Listet Dateien ab oder bis zu einer beliebigen Größe in einem beliebigen Verzeichnis. .DESCRIPTION Listet entweder kleine Dateien oder große Dateien bis zu einer festgelegten Größe in einem beliebigen Verzeichnis, das Sie festlegen. Die Ausgabe wird absteigend nach Dateigröße sortiert. Verwenden Sie die Funktion ohne Parameter, erhalten Sie größere Dateien ab 100 KB im Installationsverzeichnis der PowerShell. .PARAMETER Ort Legt das zu durchsuchende Verzeichnis fest. Geben Sie einen gültigen absoluten oder relativen Pfad an. .PARAMETER Groesse Legt die Dateigröße fest, ab der oder bis zu der die Ausgabe erfolgen soll. .PARAMETER Klein Wird der Parameter angegeben, werden nur kleinere Dateien angezeigt. Lassen Sie den Parameter weg, erhalten Sie größere oder gleichgroße Dateien. .EXAMPLE Get-AD_Files Die Funktion wird mit den Standardwerten ausgeführt. Sie erhalten die Ausgabe aller Dateien des Installationsverzeichnisses der PowerShell, die mindestens 100 KB groß sind. .EXAMPLE Get-AD_Files -Klein Die Verwendung von -Klein kehrt die Ausgabe um. Sie sehen jetzt nur die Dateien, die kleiner als 100 KB sind. .EXAMPLE Get-AD_Files -Ort C:\Windows\System32 -Groesse 25MB Sie erhalten die Ausgabe: -a---- 13.03.2019 16:54 127411920 MRT.exe -a---- 12.04.2018 01:33 32551944 WindowsCodecsRaw.dll .LINK Get-ChildItem #> param ($Ort = $PSHOME, $Groesse = 100kb, [switch]$Klein) if ($Klein) {$operator = ' -lt '} else {$operator = ' -ge '} $befehl = 'Get-ChildItem $Ort | Where-Object {$_.Length' + $operator + '$Groesse -and !$_.PSIsContainer} | Sort-Object -Property Length -Descending' Invoke-Expression $befehl } (Get-ChildItem –Path Function:Clear-Host).Definition function Get-AD_Return { $a = 67 * 5 $b = "Guten Tag" $b return $a } filter GroesserAls ([int]$groesse) { $_ | Where-Object { $_.Length –gt $groesse } } Get-ChildItem –Path C:\Windows\system32 | GroesserAls 22MB filter WordBearbeitet ([int]$tage) { $_ | Where-Object { ($_.Extension -eq ".docx") -and (((Get-Date) - $_.LastWriteTime).Days -lt $tage)} } Get-ChildItem –Path ./Projekt/ -Recurse | WordBearbeitet 3 KAPITEL 14 ========== Start-Transcript –Path $HOME\Desktop\mylog.txt Stop-Transcript Get-CimInstance -ClassName Win32_Account Compress-Archive –Path $HOME\Grafik\*.jpg –CompressionLevel Optimal –DestinationPath $HOME\Desktop\Archiv.zip https://docs.microsoft.com/en-us/powershell/module/?view=powershell-6 Get-Module –Name PSReadLine | Get-Member –MemberType Property Get-Module -Name PSReadLine | Select-Object -Property Name, Author, CompanyName, Description, HelpInfoUri, Path, PowerShellVersion, RootModule, Version $env:PSModulePath $env:PSModulePath –split ";" $env:PSModulePath –split ":" $env:PSModulePath += ";absoluter Pfad" $env:PSModulePath += ":absoluter Pfad" https://www.powershellgallery.com https://www.chocolatey.org Register-PackageSource -Name Chocolatey -Provider PowerShellGet -Location https://chocolatey.org/api/v2/ Get-PackageProvider Get-PSRepository Find-Module –Tag subnet Find-Module –Filter subnet Save-Module –Name Indented.Net.IP –Path .\ZumTesten\ Install-Module –Name Indented.Net.IP Get-Module –ListAvailable –Name Indent* Get-Command –Module Indented.Net.IP Get-Subnet -IPAddress 192.168.0.1 -SubnetMask 255.255.255.0 -NewSubnetMask 255.255.255.192 Uninstall-Module –Name Indented.Net.IP Find-Module –Name NewRandomPassword Save-Module –Name NewRandomPassword –Path $HOME\Desktop\ Get-Module –ListAvailable –Name NewRandomPassword Get-Help New-RandomPassword New-RandomPassword New-RandomPassword –Count 15 New-RandomPassword –PasswordLength 16 New-RandomPassword -MinimumLength 8 -MaximumLength 16 -FirstCharacter "8" -Count 10 function Get-AD_Mwst ([double]$betrag) { $mwst = $betrag * .19 "MwSt. für {0:c} = {1:c}" -f $betrag, $mwst "Gesamtsumme mit MwSt. = {0:c}" -f ($betrag + $mwst) } function Get-AD_Message { "Meldung aus dem Modul AD_Basics..." } New-Item –ItemType Directory $HOME\Desktop\AD_Basics New-Item -ItemType File C:\Users\AD\Desktop\AD_Basics\AD_Basics.psm1 Set-Content -Path C:\Users\AD\Desktop\AD_Basics\AD_Basics.psm1 -Value '. $PSScriptRoot\simple_funktionen.ps1' Import-Module –Name $HOME\Desktop\AD_Basics Get-Module Get-AD_Mwst 1000 Get-AD_Message New-ModuleManifest –Path $HOME\Desktop\AD_Basics\AD_Basics.psd1 RootModule = 'AD_Basics.psm1' FunctionsToExport = @('Get-AD_Mwst','Get-AD_Message') Import-Module –Name $HOME\Desktop\AD_Basics –Force Get-Module Get-Module -Name AD_Basics | Select-Object -Property Name, Author, Copyright, Path, RootModule, Version Test-ModuleManifest https://docs.microsoft.com/en-us/powershell/developer/module/how-to-write-a-powershellmodule-manifest https://docs.microsoft.com/de-de/powershell/gallery/how-to/publishing-packages/publishing-a-package KAPITEL 15 ========== Write-Host "Ausgabe vorher." 1..10 | foreach {$_ Write-Host "Ausgabe nachher." Write-Host "Ausgabe vorher." Get-Content –Path .\gibtsnicht.txt Write-Host "Ausgabe nachher." Get-Process –Name GibtsNicht Get-Process –Name GibtsNicht –ErrorAction SilentlyContinue Get-Process –Name GibtsNicht –ea 0 Get-ChildItem C:\Windows\System32\ -Directory -Recurse | Select-Object -Property Name Get-ChildItem C:\Windows\System32\ -Directory –Recurse –ErrorAction SilentlyContinue | Select-Object -Property Name $ErrorActionPreference = "Silently Continue" 34 * "Huhn" $Error[0].Exception.InnerException.GetType().FullName New-Item –Path .\log.txt –ItemType File if ($?) { Write-Host "Protokolldatei erfolgreich angelegt." } else { Write-Host "Datei konnte nicht angelegt werden." } try { 1/0 } catch { Write-Host "Ein Fehler ist aufgetreten." Write-Host "Fehlertyp:" $_.Exception.GetType().FullName if ($_.Exception.InnerException) { Write-Host "Fehlertyp (genauer):" $_.Exception.InnerException.GetType().FullName } Write-Host "Fehlernachricht:" $_.Exception.Message } try { Get-Content –Path .\try.ps # vertippt, statt .\try.ps1 } catch { Write-Host "Ein Fehler ist aufgetreten." } try { Get-Content –Path .\try.ps –ErrorAction Stop } catch { Write-Host "Fehler: $_" } try { $ErrorActionPreference = "Stop" Get-Content –Path .\try.ps 1/0 netshell #unbekannt } catch { Write-Host "Erster gefundener Fehler: $_" } $ErrorActionPreference = "Stop" try { Get-Content –Path .\try.ps } catch { Write-Host "Fehler (catch-Block 1): $_" } try { 1/1 } catch { Write-Host "Fehler (catch-Block 2): $_" } try { netshell } catch { Write-Host "Fehler (catch-Block 3): $_" } try { $AlteEinstellung = $ErrorActionPreference $ErrorActionPreference = "Stop" #Anweisungen } catch { #Anweisungen } finally { $ErrorActionPreference = $AlteEinstellung } try { 1/0 } catch [System.DivideByZeroException] { Write-Host "Ausgabe catch-Block 'DivideByZeroException'" } catch [System.Management.Automation.RuntimeException] { Write-Host "Ausgabe catch-Block 'RuntimeException'" } function Do-AD_TrapTest { trap { Write-Host "Fehler in der Funktion gefunden: $_" -ForegroundColor White -BackgroundColor Red continue } Write-Host "Noch kein Fehler in der Funktion" Get-Process -Name unbekannt -ErrorAction Stop #FEHLER Write-Host "Ausführung nach dem Fehler in der Funktion" } Write-Host "Starte Ausführung des Skripts" Do-AD_TrapTest Write-Host "Beende Ausführung des Skripts" $AlteEinstellung = $ErrorActionPreference $ErrorActionPreference = "Stop" trap { Write-Host "Fehler: $_" continue } #Fehlerteil: ein Fehler nach dem anderen 1/0 #Division durch null Get-Content .\try.ps #falscher Dateiname Get-Process -Name unbekannt #nicht vorhandener Prozess netshell #unbekannter Befehl $ErrorActionPreference = $AlteEinstellung #"aufräumen" throw throw "OH NEIN" throw (Get-Process –Name pwsh) throw (New-Item -ItemType File -Path .\test.txt) $Error[0].TargetObject throw [System.AccessViolationException] "Kein Zugriff" KAPITEL 16 ========== Get-ChildItem WSMan:\localhost\Client\TrustedHosts Start-Service –Name WinRM Set-Item WSMan:\localhost\Client\TrustedHosts –Value * Set-Item WSMan:\localhost\Client\TrustedHosts –Value 192.168.182.133 Set-Item WSMan:\localhost\Client\TrustedHosts –Value 192.168.182.* Enable-PSRemoting Enable-PSRemoting –SkipNetworkProfileCheck –Force Test-WSMan –ComputerName Zielrechner https://github.com/Microsoft/omi https://github.com/PowerShell/psl-omi-provider Disable-PSRemoting https://docs.microsoft.com/de-de/powershell/scripting/core-powershell/ssh-remoting-inpowershell-core?view=powershell-6 https://docs.microsoft.com/de-de/windows-server/administration/openssh/openssh_overview https://github.com/PowerShell/Win32-OpenSSH Start-Service sshd Set-Service –Name sshd –StartupType Automatic sudo apt-get install openssh-server sudo gedit sshd_config sudo service sshd restart. sudo launchctl stop com.openssh.sshd sudo launchctl start com-openssh.sshd Get-Command –ParameterName ComputerName Stop-Computer –ComputerName Server01, Server02 -Force $creds = Get-Credential Invoke-Command -ComputerName Client10-1 -Credential $creds -ScriptBlock {Stop-Computer -Force} Invoke-Command -ComputerName Client10-1 -Credential "AD" -ScriptBlock {hostname; whoami} $anweisungen = { Beliebig viele Anweisungen } Invoke-Command –ComputerName Client10-1 – ScriptBlock $anweisungen Invoke-Command -ComputerName Client10-1 -Credential "AD" -ScriptBlock {Get-Process -Name p*,w*} Invoke-Command -HostName 192.168.182.132 -UserName ad -ScriptBlock {hostname} Invoke-Command -HostName AD@ubuntu01 -ScriptBlock { $PSVersionTable } Invoke-Command –ComputerName Client10-1 –Credential "AD" –FilePath C:\Skripte\take-over-the-world.ps1 Invoke-Command -HostName AD@ubuntu01 –FilePath \\BrainSource\takeover-the-world.ps1 Invoke-Command –ComputerName Client10-1 –ScriptBlock { Set-ExecutionPolicy –ExecutionPolicy Unrestricted } Enter-PSSession –ComputerName Client10-1 –Credential "AD" Enter-PSSession –HostName 192.168.182.131 –UserName ad -SSHTransport $ubuntu = New-PSSession -HostName 192.168.182.131 -UserName ad –SSHTransport Invoke-Command -Session $ubuntu -ScriptBlock { $remotewert = 67 } $remotewert Invoke-Command -Session $ubuntu -ScriptBlock { $remotewert } New-PSSession -HostName 192.168.182.131 -UserName ad $macAD = New-PSSession –HostName 192.168.182.129 –UserName ad –SSHTransport $ubuntu01= New-PSSession –HostName 192.168.182.132 –UserName Georg –SSHTransport Get-PSSession | Format-List $creds = Get-Credential $Sitzung = New-PSSession -ComputerName Client10-1 -Credential $creds Invoke-Command -Session $Sitzung -ScriptBlock { Get-Culture } $ubuntu01= New-PSSession –HostName 192.168.182.132 –UserName Georg –SSHTransport Invoke-Command –Session $ubuntu01 –FilePath \\BrainSource\take-over-the-world.ps1 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-6 Enter-PSSession Exit-PSSession Get-PSSession New-PSSession Remove-PSSession KAPITEL 17 ========== $NeuesObjekt = [Klassenname]::new(Parameter1, ParameterN) $NeuesObjekt = New-Object –TypeName Klassenname –ArgumentList Parameter1, ParameterN $NeuesObjekt | Get-Member $NeuesObjekt.Attribut $NeuesObjekt.Methode() class Dummy { #hier steht nix } $DummyTest = [Dummy]::new() $DummyTest.GetType().IsClass class MAHochbau { [int] $ArmeAnzahl [int] $BeineAnzahl [string] $Vorname [string] $Nachname [int] $Alter [double] $Groesse #... } $Martin = [MAHochbau]::new() $Martin $Martin.ArmeAnzahl = 2 $Martin.Vorname = "Martin" #hier auf Anführungszeichen achten class MAHochbau { [int] $ArmeAnzahl = 2 [int] $BeineAnzahl = 2 [string] $Vorname [string] $Nachname [int] $Alter [double] $Groesse #... } static [string]$Beschreibung = "Mitarbeiterinnen und Mitarbeiter des Hochbaus" class Auto { [string]$Hersteller [string]$Modell [string]$Farbe [string]$Kennzeichen static [int]$RadAnzahl = 4 #ja, es gibt auch 3 oder 6 [int]$TuerAnzahl [int]$Baujahr [int]$Tankinhalt [int]$KmStand [void]Tanken([int]$Getankt) { $this.Tankinhalt += $Getankt } [void]Fahren([int]$Km) { if ($this.Tankinhalt –gt 10) { $this.KmStand += $Km $this.Tankinhalt -= [int]($Km/10) } if ($this.Tankinhalt -le 10) { Write-Warning "Tanken!!!" } } } $MeinAuto = [Auto]::new() $MeinAuto.Baujahr = 2007 $MeinAuto.Hersteller = "Horch" $MeinAuto.Tanken(25) $MeinAuto.Fahren(200) class Test { [void]SayHi() { $Text = "Guten Morgen" $Text } [string]SayHello() { return "Guten Morgen" } } $neu = [Test]::new() $neu.SayHi() $neu.SayHello() class Test { [void]AchtVoid() { $wert = 8 $wert } [int]Acht() { $wert = 8 return $wert } [int[]]Zehn() { return 1..10 } } $neu.AchtVoid() $neu.Acht() $neu.Zehn() class Mitarbeiter { [string]$Vorname [string]$Nachname [int]$Alter #weitere Attribute und Methoden } [Mitarbeiter]::new() | Get-Member [Mitarbeiter]::new() | Get-Member -Force $Cengiz ($Cengiz = [Mitarbeiter]::new()) $Cengiz.Vorname $Cengiz.get_Vorname() class Auto { #...Attribute und Methoden wie bisher Auto([string] $HerstellerEingabe) { $this.Hersteller = $HerstellerEingabe } } $MeinAuto = [Auto]::new() $MeinAuto = [Auto]::new("Horch") class Auto { #Attribute und Methoden wie bisher #aus Platzgründen hier ausgelassen Auto() { } Auto([string] $HerstellerEingabe) { $this.Hersteller = $HerstellerEingabe } Auto([string]$HerstellerEingabe, [string]$ModellEingabe) { $this.Hersteller = $HerstellerEingabe $this.Modell = $ModellEingabe } Auto([string]$HerstellerEingabe, [string]$ModellEingabe, [int]$BaujahrEingabe) { $this.Hersteller = $HerstellerEingabe $this.Modell = $ModellEingabe $this.Baujahr = $BaujahrEingabe } } $a = [Auto]::new() $b = [Auto]::new("Horch") $c = [Auto]::new("Horch", "853 Cabriolet") $d = [Auto]::new("Horch", "853 Cabriolet", 1932) [Auto]::new class Fahrzeug { [string] $Hersteller [int] $KmStand #Methoden } class Auto : Fahrzeug { [int]RadAnzahl Auto([string]$HerstellerEingabe, [int]$KmStandEingabe) { $this.Name = $HerstellerEingabe $this.KmStand = $KmStandEingabe } } class Mensch { [int]$Alter Mensch([int]$AlterEingabe) { $this.Alter = $AlterEingabe } } class Kind : Mensch { [string]$Schule Kind([int]$AlterEingabe, [string]$SchuleEingabe) : base($AlterEingabe) { $this.Schule = $SchuleEingabe } } $Lena = [Kind]::new(12, "Albert-Schweitzer-Schule") class Fahrzeug { [int] $KmStand [void] Fahren([int] $KmAnzahl) { Write-Host -Object ('Gerade {0} km gefahren.' -f $KmAnzahl) -ForegroundColor Red $this.KmStand += $KmAnzahl } } class Auto : Fahrzeug { [int] $RadAnzahl # Methode Fahren() überschreibt vererbte Methode [void] Fahren([int] $KmAnzahl) { Write-Host -Object ('Gerade {0} km gefahren.' -f $KmAnzahl) -ForegroundColor Green $this.KmStand += $KmAnzahl #zusätzlich Methode der Basisklasse aufrufen ([Fahrzeug]$this).Fahren($KmAnzahl) } } enum Farbe { Blau Grau Braun Grün } class Mensch { [string]$Vorname [Farbe]$Augenfarbe [int]$Alter Mensch([Farbe]$AugenfarbeEingabe) { $this.Augenfarbe = $AugenfarbeEingabe } } $Marie = [Mensch]::new("Braun") $Marie = [Mensch]::new(2) $Marie.Energie(100) $Marie.Laufen(5) $Marie.Frühstück() $Marie.Arbeiten(8) $Marie.Ausruhen() KAPITEL 18 ========== function Start-AD_Testing { $ZeitStempel = Get-Date -Format "yyyyMMdd_HHmmss" Start-Transcript -Path $HOME\PS-Protokolle\mitschrift$ZeitStempel.log } $PSDefaultParameterValues.Add('Remove-Item:Confirm', $True) $PSDefaultParameterValues.Clear() https://code.visualstudio.com/docs https://docs.microsoft.com/en-us/powershell/ https://github.com/PowerShell/PowerShell/releases https://github.com/psconfeu/ https://www.powershellgallery.com https://docs.microsoft.com/de-de/powershell/scripting/whats-new/known-issues-ps6?view=powershell-6 https://github.com/psconfeu/2018/tree/master/Bruce%20Payette KAPITEL 19 ========== Get-Process –Name "pwsh" –FileVersionInfo $Argumente = { Name = "pwsh" FileVersionInfo = $True } Get-Process @Argumente $Argumente = { DomainName = "test.local" DomainNetbiosName = "TEST" ForestMode = "Windows Server 2016" DomainMode = "Windows Server 2016" InstallDns = $True CreateDnsDelegation = $False LogPath = "C:\Windows\NTDS" DatabasePath = "C:\Windows\NTDS" SysvolPath = "C:\Windows\SYSVOL" SafeModeAdministratorPassword = (ConvertTo-SecureString -AsPlainText "TestPassword1" -Force) NoRebootOnCompletion = $False Force = $True } Install-ADForest @Argumente Get-Process –Name "pwsh" Get-Process –Name "pwsh" | Select-Object –Property * (Get-Process –Name "pwsh").Threads Get-Process –Name "pwsh" | Select-Object –ExpandProperty Threads Get-ChildItem -Path C:\Windows\System32 | Where-Object {$_.Length -gt 25MB} | Select-Object -Property Name, Length, @{Name='in kB'; Expression={[math]::round($_.Length/1KB)}}, @{Name='in MB'; Expression={[math]::round($_.Length/1MB)}} | Format-Table -AutoSize Get-ChildItem -Path .\*.ps1 | Select-Object -Property Name,@{Name="TagErstellung"; Expression = {"{0:dddd}" -f $_.CreationTime}} | Sort-Object -Property TagErstellung $MyCreds = Get-Credential Get-Command -ParameterName Credential 1..500 | foreach { Write-Host "$(Get-Random –Minimum 5 –Maximum 6) " -NoNewline } Get-Random –Minimum 1 –Maximum 7 https://github.com/Pscx/Pscx Out-Voice [Environment]::GetFolderPath("Desktop") [Environment]::MachineName [Environment]::NewLine [Environment]::UserName [IO.Path]::GetTempPath() [IO.Path]::PathSeparator Out-GridView Get-ADUser –Filter * | Set-ADObject –protectedFromAccidentalDeletion $True https://www.powershellgallery.com