Private/Wissen/C_Advance/C09_ScriptAutostart.ps1

<#
 
# Autostartdateien
 
PowerShell-Code beim starten eine Session automatisch ausführen.
 
- **Hashtags** profile prompt exe link start auto GPO
- **Version** 2021.08.26
 
#>


# ! - Code der in den u.a. Dateien steht wird automatisch ausgeführt wenn
# ! eine PowerShell-Session (Remote, Host, Anwendung) startet.
# ! - Die u.a. Ordner/Dateien müssen zu erst erstellt werden.
# ! - ZWECK: Um seine PS-Umgebung 'gemütlich' einzurichten:
$profile.AllUsersAllHosts        # * z.B. C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
$profile.AllUsersCurrentHost     # * z.B. C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.VSCode_profile.ps1
$profile.CurrentUserAllHosts     # * z.B. C:\Users\Administrator\Documents\WindowsPowerShell\profile.ps1
$profile.CurrentUserCurrentHost  # * z.B. C:\Users\Administrator\Documents\WindowsPowerShell\Microsoft.VSCode_profile.ps1

# *
# * z.B. das ständige Ausführen einer *.ps1-Datei
# *

Get-ChildItem -Path Function:\prompt | Select-Object -ExpandProperty Definition
# ! könnte man verbessern in:
Add-Content -Force -Path $profile.CurrentUserAllHosts -Value @'
function Prompt {
    $lastCmd = Get-History -Count 1
    if ($null -ne $lastCmd) {
        $timeSpan = $lastCmd.EndExecutionTime - $lastCmd.StartExecutionTime
        "[ {0}h {1}m {2}s {3}ms ] {4} " -f $timeSpan.Hours, $timeSpan.Minutes, $timeSpan.Seconds, $timeSpan.Milliseconds, $executionContext.SessionState.Path.CurrentLocation |
          Write-Host -NoNewline
      } else {
        "[ 0 ms ] $($executionContext.SessionState.Path.CurrentLocation) " | Write-Host -NoNewline
    }
}
'@


#region Semi-Automatisch

# Per Rechts-Klick auf eine .PS1-Datei

# ... per Aufruf in der Console (s. Call Operators)
& 'c:\temp\Test.ps1' # Der enthaltene Code wird in einem GETRENNTEN Context ausgeführt => #TODO Für das laden von insich geschlossenen SKripten
. 'c:\temp\Test.ps1' # Der enthaltene Code gehört zum aktuell Ausführungs-Context => #TODO Für das Laden von Cmdlets sowie gewollte Manipulationen an der aktuellen Session.

# Zum Beispiel:
$wichtig = 'Hallo Köln!'
& {  $wichtig = 'Hallo Würzburg!' } # ! Die Variable $wichtig in der aktuellen Sitzung wird NICHT verändert!
$wichtig
. {  $wichtig = 'Hallo Würzburg!' } # ! Die Variable $wichtig in der aktuellen Sitzung wird GEÄNDERT!
$wichtig

# ... per Datei-Verknüpfung auf:
powershell.exe -File 'c:\temp\Test.ps1' -WindowStyle Hidden
powershell.exe -File 'c:\temp\Test.ps1' -NoExit
powershell.exe -File 'c:\temp\Test.ps1' -ExecutionPolicy ByPass
# ! PowerShell 7
& 'C:\Program Files\PowerShell\7\pwsh.exe' -File 'c:\temp\Get-EuroExchange.ps1' -NoExit

# ... per RUN-Schlüssel
# ... per GPO
# ... per Windows Aufgabenplanung
# ... per Module (.PSM1-Datei) (i.d.R. die beste Variante)

#endregion