All posts tagged Kommandozeile

Hallo zusammen,

in dem heutigen Howto zeige ich euch ein kleines Powershell Skript, wie Ihr Logdateien in Realtime monitoren könnt.
Folgenden Zeilen im Skript sollten angepasst werden, über diese Variablen könnt Ihr das Monitoring steuern.

Im Header des Skripts habe ich den Ablauf dokumentiert, sollten noch Fragen aufkommen, Ihr wisst wie Ihr mich erreichen könnt.

## $EmailPasswortFile = "D:\PowershellScripte\MailPasswort.txt"
$LogFiletoCheck = "D:\PowershellScripte\MyLogFiles.txt"
$ScriptSleepTimeOut = 10 ## 10 Sekunden Pause in der Skript Schleife
$ScriptLoopTime = 5 ## 5 Minuten Skriptlaufzeit
$EventCheckCount = 15 ## Überprüft das Dienstprotokoll nach der Anzahl der Ereignisse, hier Maximal 15 Einträge
$EventTimeRange = 30 ## Zeitspanne für die Anzahl der Ereignisse, wenn mehr als 15 Einträge in 30 Minuten geschrieben werden, mach irgendwas (z.B. E-Mail versenden)
#########################################################################################################
##
## Name: Log Datei überwachung, Ergebnisse ins Dienstprotokoll schreiben                            
## Ersteller: Helmut Thurnhofer                    
## Erstellungsdatum: 05.01.2016                                                             
## Version: 1.0
##
#######################################################
## Skriptbeschreibung und Vorbereitung auf dem Server:
#######################################################
##
## Um mit dem Skript arbeiten zu können müssen ein paar Vorbereitungen auf dem Server getroffen werden.
## Zum einem muss die ExecutionPolicy für den auszuführenden Benutzer gesetzt werden und zum zweiten wird in der Ereignisanzeige
## ein neues Dienstprotokoll angelegt. (Zu finden unter Anwendungs- und Dienstprotokoll)
##
## Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force 
## (Die Powershell wird keine Skripte ausführen, die aus dem Internet stammen – Für unsere Aufgabe beste Wahl.)
##
## Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force 
## (Die Powershell ignoriert die digitale Signatur, fragt aber nach, ob ein Skript, das aus dem Internet stammt, ausgeführt werden soll.)
##
###################################################
## Dienstprotokoll anlegen mit folgenden Befehlen:
###################################################
##    
## New-EventLog -LogName MeinServerLog -Source Error,Fatal,Warning,Information
## Limit-EventLog -LogName MeinServerLog -MaximumSize 10485760 -OverflowAction OverwriteAsNeeded
##
## -MaximumSize 524288 = 512KB
## -MaximumSize 1048576 = 1024KB = 1MB
## -MaximumSize 10485760 = 10240KB = 10MB
## -MaximumSize 20971520 = 20480KB = 20MB
##
################################################################
## Testeinträge in das neu erstellte Dienstprotokoll schreiben:
################################################################
##
## Write-EventLog -LogName MeinServerLog -Source Information -EntryType Information -EventId 1000 -Message "Information über die PowerShell"
## Write-EventLog -LogName MeinServerLog -Source Warning -EntryType Warning -EventId 2000 -Message "Warning über die PowerShell"
## Write-EventLog -LogName MeinServerLog -Source Error -EntryType Error -EventId 3000 -Message "Error über die PowerShell"
## Write-EventLog -LogName MeinServerLog -Source Fatal -EntryType Error -EventId 4000 -Message "Fatal über die PowerShell"
##
## Für die Events wurde eigene EventIDs verwendet, Information=1000, Warnungen=2000, Error=3000, Fatal=4000
##
#############################################
## Testeinträge im Dienstprotokoll abfragen:
#############################################
##
## Get-EventLog -LogName MeinServerLog -InstanceId 3000,4000 -Newest 20
##
## $DateNow = Get-Date
## $Time30Minutes = (Get-Date).AddMinutes(-30)
## Get-EventLog -LogName MeinServerLog -EntryType Error -Before $DateNow -After $Time30Minutes
##
## Get-EventLog -LogName MeinServerLog -Source Fatal,Error
## Get-EventLog -List
##
##############################################################################################################
## Um das ganze Simulieren zu können, wurde eine leere Log Datei erstellt und mit folgenden Einträgen gefüllt.
## Die Einträge wurden Zeitversetzt über eine zweite Powershell Sitzung ausgeführt.
##############################################################################################################
##
## $Date = Get-Date
## $DateTime = $Date.ToString("yyyy-MM-dd HH:mm:ss")
## Add-Content "D:\PowershellScripte\MyLogFiles.txt" -Value "$DateTime - FATAL: 0x80070490: EvaluateApplicability failed in CCbs::EvaluateApplicability"
##
## $Date = Get-Date
## $DateTime = $Date.ToString("yyyy-MM-dd HH:mm:ss")
## Add-Content "D:\PowershellScripte\MyLogFiles.txt" -Value "$DateTime - ERROR: 0x80070432: Forced install timer expired for AUInstallType = 4"
##
## $Date = Get-Date
## $DateTime = $Date.ToString("yyyy-MM-dd HH:mm:ss")
## Add-Content "D:\PowershellScripte\MyLogFiles.txt" -Value "$DateTime - Information: 0x80000000: Successfully wrote event for AU health state:0"
## 
## $Date = Get-Date
## $DateTime = $Date.ToString("yyyy-MM-dd HH:mm:ss")
## Add-Content "D:\PowershellScripte\MyLogFiles.txt" -Value "$DateTime - Warning: 0x80202000: Warning event for AU health state were 3"
##
######################################################################
## Bitte diese Zeilen vor dem ersten Lauf im Skript ausführen, 
## Hier wird das E-Mail Benutzer Passwort als String in einen Textdatei geschrieben.
## Diese Textdatei wird für den späteren E-Mail versandt benötigt.
######################################################################
##
## (Get-Credential).Password | ConvertFrom-SecureString > $EmailPasswortFile
##
#########################################################################################################
Clear-Host

## Basisparameter für das Skript
##
## $EmailPasswortFile = "D:\PowershellScripte\MailPasswort.txt"
$LogFiletoCheck = "D:\PowershellScripte\MyLogFiles.txt"
$ScriptSleepTimeOut = 10 ## 10 Sekunden Pause in der Skript Schleife
$ScriptLoopTime = 5 ## 5 Minuten Skriptlaufzeit
$EventCheckCount = 15 ## Überprüft das Dienstprotokoll nach der Anzahl der Ereignisse, hier Maximal 15 Einträge
$EventTimeRange = 30 ## Zeitspanne für die Anzahl der Ereignisse, wenn mehr als 15 Einträge in 30 Minuten geschrieben werden, mach irgendwas (E-Mail versenden)
##
#########################################################################################################


## Basis E-Mail Server Konfiguration
##
## $ServerName = "$env:COMPUTERNAME.$env:USERDOMAIN"
## $KundenName = "Musterkunde Deutschland GmbH"
## $SMTPServer = "smtp.domain.de"
## $SMTPUserName = "Benutzername"
## Bitte diese Skriptzeile vorab ausführen damit die EmailPasswort datei erstellt wird.
##
## (Get-Credential).Password | ConvertFrom-SecureString > $EmailPasswortFile
## $SMTPUserPwd = Get-Content -Path $MailPasswortFile | ConvertTo-SecureString
## $Cred = New-Object System.Management.Automation.PSCredential $SMTPUserName, $SMTPUserPwd
##
## Basisinformationen für den E-Mail versandt.
##
## $EmailTo = empfaenger@domain.de
## $EmailFrom = absender@domain.de
## $EmailSubject = "Es wurde beim `"$KundenName`" mehr als 15 Fatal/Error Einträge in den Logs gefunden. Bitte Server: `"$ServerName`" überprüfen!"
## $EmailBody ist weiter unten im Skript definiert, da hier die Auswertung der Variaben benötigt werden.
#########################################################################################################


$LoopStartTime = Get-Date
$LoopStartTimeFormatted = $LoopStartTime.ToString("dd.MM.yyyy HH:mm:ss")

$LoopEndTime = $LoopStartTime.AddMinutes($ScriptLoopTime)
$LoopEndTimeFormatted = $LoopEndTime.ToString("dd.MM.yyyy HH:mm:ss")
## $LoopEndTime = $LoopStartTime.AddHours($ScriptLoopTime)
## $LoopEndTimeFormated = $LoopEndTime.ToString("dd.MM.yyyy HH:mm:ss")

Write-Host "`nRealtime LogFile Monitoring wurde gestartet um: $LoopStartTimeFormatted" -ForegroundColor Gray
write-host "Realtime LogFile Monitoring wird beendet um: $LoopEndTimeFormatted`n" -ForegroundColor Gray
#########################################################################################################

## Alle 10 Sekunden wird die Schleife wiederholt, bei einem Treffer im Log wird ein Ereigniseintrag geschrieben
## Wenn mehr als 15 Einträge in 30 Minuten geschrieben werden, wird eine E-Mail Versand.
## Skript Idee -- http://sion-it.co.uk/tech/powershell/loop-until-a-certain-time

Do { 
     ## Hier wird pro Schleifendurchlauf die Aktuelle Zeit geholt und neu gesetzt
     ##
     $LoopTimeNow = Get-Date
     $LoopTimeNowFormatted = $LoopTimeNow.ToString("dd.MM.yyyy HH:mm:ss")

     ## Diese Zeitangabe wird für die Suche in der Log Datei benötigt, wenn hier Einträge älter/gleich Suchzeit ist.
     ## Wird ein neuer Dienstprotokoll Eintrag geschrieben, diese Zeit sollte mit der Skriptpause übereinstimmen,
     ## ansonsten werden hier wo wöglich neue Einträge in der Log nicht gefunden, das Sie aus der Zeitrange fallen.
     ##
     $SearchTime = (Get-Date).AddSeconds(-$ScriptSleepTimeOut)
     $SearchTimeInLog = $SearchTime.ToString("yyyy-MM-dd HH:mm:ss")

     If ($LoopTimeNow -ge $LoopEndTime) {
        Write-host "Endzeit: `"$LoopEndTimeFormatted`" ist erreicht, Skript wird im nächsten Durchgang beenden."
 
     } Else {
        
        ## Überprüft die Einträge in der Log Datei, sollte was gefunden werden, wird es an die ForEach Schleife übergeben und in das Dienstprotokoll geschrieben.
        ##
        [string[]]$FatalMessages = Get-Content $LogFiletoCheck | Where-Object {($_ -ge $SearchTimeInLog) -and $_ -match "FATAL"}
        [string[]]$ErrorMessages = Get-Content $LogFiletoCheck | Where-Object {($_ -ge $SearchTimeInLog) -and $_ -match "ERROR"}
        [string[]]$WarningMessages = Get-Content $LogFiletoCheck | Where-Object {($_ -ge $SearchTimeInLog) -and $_ -match "Warning"}

        ForEach ($FatalMessage in $FatalMessages) {
        Write-EventLog -LogName enaioServerLog -Source Fatal -EntryType Error -EventId 4000 -Message "$FatalMessage"
        Write-Host "Ereigniseintrag `"$FatalMessage`" wurde erstellt." -ForegroundColor DarkRed     
        }

        ForEach ($ErrorMessage in $ErrorMessages) {
        Write-EventLog -LogName enaioServerLog -Source Error -EntryType Error -EventId 3000 -Message "$ErrorMessage"
        Write-Host "Ereigniseintrag `"$ErrorMessage`" wurde erstellt." -ForegroundColor DarkRed     
        }

        ForEach ($WarningMessage in $WarningMessages) {
        Write-EventLog -LogName enaioServerLog -Source Warning -EntryType Warning -EventId 2000 -Message "$WarningMessage"
        Write-Host "Ereigniseintrag `"$WarningMessage`" wurde erstellt." -ForegroundColor DarkYellow     
        }
            
            ## Überprüfe das Dienstprotokoll, wenn mehr als 15 Einträge in 30 Minuten geschrieben wurden, wird eine E-Mail an den Administrator versendet.
            ##
            $Count = $EventCheckCount
            $DateNow = Get-Date
            $Time30Minutes = (Get-Date).AddMinutes(-$EventTimeRange)
            $EventDate = $Time30Minutes.ToString("yyyy-MM-dd HH:mm:ss")
            $EventCount = (Get-EventLog -LogName enaioServerLog -InstanceId 3000,4000 -Before $DateNow -After $Time30Minutes).Count
            ## $EmailBody = "In den letzten 30 Minuten sind mehr als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden."
                    
            If($EventCount -ge $Count) {
                   
                Write-Host "`nIn den letzten 30 Minuten sind mehr als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden." -ForegroundColor DarkRed
                Write-Host "E-Mail wird versendet, da mehr als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden sind." -ForegroundColor DarkRed
                ## Aktion einfügen wie z.B. Mail versandt
                ##
                ## Send-MailMessage -Credential $Cred -SmtpServer $SMTPServer -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body $EmailBody -Encoding ([System.Text.Encoding]::UTF8)
            
            } Else {

                Write-Host "`nIn den letzten 30 Minuten sind weniger als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden." -ForegroundColor DarkGreen
                Write-Host "E-Mail wird nicht versendet, da weniger als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden sind." -ForegroundColor DarkGreen
            }

        ## Statusmeldung, wie lange das Skript noch ausgeführt wird
        ##
        Write-Host "Skript wird noch nicht beendet, es läuft noch bis `"$LoopEndTimeFormatted`"" -ForegroundColor Gray
     }

 ## Skriptpause bis die Schleife wiederholt wird
 ##
 Start-Sleep -Seconds $ScriptSleepTimeOut

}
## Skript wird nach Erreichen der Angegeben Zeit beendet
##
Until ($LoopTimeNow -ge $LoopEndTime)

Wie immer freue ich mich über Kommentare und Anregungen.

Viele Grüße
Helmut

Hallo zusammen,

in dem heutigen Howto zeige ich euch ein kleines Skript, wie Ihr eure Powershell Umgebung auf allen Computern/Server gleich setzen könnt.

Powershell_Konsole

 

 

 

 

 

Powershell_Konsole_2

 

 

 

 

 

Bitte vor der Skript Ausführung eure ExecutionPolicy setzen

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force

Damit Powershell immer ein Startverzeichnis hat, bitte die passende Variable im Skript setzen

$StartFolder="C:\ oder D:\DeinVerzeichnis"

Und hier das Skript

#######################################################################################
## Skript:  Powershell Profil Datei anlegen
## Name:    Helmut Thurnhofer
## Datum:   03.01.2016
## Version: 1.0
##
## Powershell Konsolen Anpassung
## https://tobivnext.wordpress.com/2012/03/07/powershell-konsoleneigenschaften-anpassen/
##
## Bitte vor Skriptausführung ExecutionPolicy setzen
## Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force
##
## Bitte auch einen passenden Startverzeichnis für Powershell setzen 
## $StartFolder="C:\ oder D:\DeinVerzeichnis"
#######################################################################################
 
## Skript Variablen definieren ########################################################
$DateTime = (Get-Date -Format g)
$ProfileFile = $PROFILE.CurrentUserAllHosts
$SplitProfileFile = Split-Path -Path $ProfileFile -Leaf -Resolve
$SplitProfilePath = Split-Path -Path $ProfileFile -Parent -Resolve
$BackupProfileFile = $SplitProfilePath + "\" + "profile.bak"
$CheckProfileFile = Test-Path -PathType Leaf $ProfileFile
$StartFolder="D:\PowershellScripte"
#######################################################################################
 
## Startverzeichnis anlegen wenn noch nicht vorhanden #################################
If (!(Test-Path -Path $StartFolder)){
 
     New-Item -Type Directory -Path $StartFolder
     Write-Host "Der Ordner $StartFolder wurde angelegt" -ForegroundColor Green
} Else {
    Write-Host "Der Ordner $StartFolder existiert bereits." -ForegroundColor Yellow
}
#######################################################################################
 
 
## Überprüfe ob alte profil.ps1 Datei vorhanden ist, wenn ja, wird diese umbenannt und neu angelegt.
If($CheckProfileFile -eq $true) {
    Rename-Item -Path $ProfileFile -NewName $BackupProfileFile
    Write-Host "Powershell Profil Datei (`"$BackupProfileFile`") wurde umbenannt!`n" -ForegroundColor Yellow
 
    New-Item -ItemType File -Force $ProfileFile
    Write-Host "Powershell Profil Datei (`"$ProfileFile`") wurde neu angelegt!`n" -ForegroundColor Green
} Else {
    New-Item -ItemType File -Force $ProfileFile
    Write-Host "Powershell Profil Datei (`"$ProfileFile`") wurde neu angelegt!`n" -ForegroundColor Green
}
#######################################################################################


## Schreibe Inhalt in die profile.ps1 Datei
Add-Content $ProfileFile -Value "#####################################################################################"
Add-Content $ProfileFile -Value "## Name: Windows PowerShell Profil"
Add-Content $ProfileFile -Value "## Ersteller: $env:USERNAME"
Add-Content $ProfileFile -Value "## Erstellungsdatum: $DateTime"
Add-Content $ProfileFile -Value "## Version: 1.0"
Add-Content $ProfileFile -Value "#####################################################################################"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Skript von http://www.zerrouki.com/powershell-profile-example"
Add-Content $ProfileFile -Value "`$IPAddress=@(Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {`$_.DefaultIpGateway})[0].IPAddress[0]"
Add-Content $ProfileFile -Value "`$PSVersion=(`$PSVersionTable.PSVersion).ToString()"
Add-Content $ProfileFile -Value "Clear-Host"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "Write-Host `"``r``n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::`" -ForegroundColor Yellow"
Add-Content $ProfileFile -Value "Write-Host `"::`" -ForegroundColor Yellow -nonewline; Write-Host `"  ComputerName: `$(`$env:COMPUTERNAME)`";"
Add-Content $ProfileFile -Value "Write-Host `"::`" -ForegroundColor Yellow -nonewline; Write-Host `"  IP-Adresse:   `$IPAddress`";"
Add-Content $ProfileFile -Value "Write-Host `"::`" -ForegroundColor Yellow -nonewline; Write-Host `"  UserName:     `$env:UserDomain\`$env:UserName`";"
Add-Content $ProfileFile -Value "Write-Host `"::`" -ForegroundColor Yellow -nonewline; Write-Host `"  Powershell:   `$PSVersion`" -NoNewline;"
Add-Content $ProfileFile -Value "Write-Host `"``r``n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::`" -ForegroundColor Yellow"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "`$AllDisk = @()"
Add-Content $ProfileFile -Value "Get-WmiObject Win32_LogicalDisk -filter `"DriveType='3'`" | ForEach-Object {"
Add-Content $ProfileFile -Value "   `$AllDisk += @(`$_ | Select @{n=`"Name`";e={`$_.Caption}},"
Add-Content $ProfileFile -Value "   @{n=`"Bezeichnung`";e={`$_.VolumeName}},"
Add-Content $ProfileFile -Value "   @{n=`"Groesse (GB)`";e={`"{0:N2}`" -f (`$_.Size/1GB)}},"
Add-Content $ProfileFile -Value "   @{n=`"Belegt (GB)`";e={`"{0:N2}`" -f ((`$_.Size/1GB) - (`$_.FreeSpace/1GB))}},"
Add-Content $ProfileFile -Value "   @{n=`"Frei (GB)`";e={`"{0:N2}`" -f (`$_.FreeSpace/1GB)}},"
Add-Content $ProfileFile -Value "   @{n=`"Frei (%)`";e={if(`$_.Size) {`"{0:N2}`" -f ((`$_.FreeSpace/1GB) / (`$_.Size/1GB) * 100 )} else {`"NAN`"} }})"
Add-Content $ProfileFile -Value "}"
Add-Content $ProfileFile -Value "`$AllDisk | Format-Table -AutoSize | Out-String"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Globale Standardvariablen setzen"
Add-Content $ProfileFile -Value "`$ErrorActionPreference = `"Continue`""
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Setzen das Startverzeichnis"
Add-Content $ProfileFile -Value "Set-Location -Path $StartFolder"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Angepasster Powershell Titel"
Add-Content $ProfileFile -Value "`$a = (Get-Host).UI.RawUI"
Add-Content $ProfileFile -Value "`$a.WindowTitle = `"HTDOM - Powershell`""
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Angepasster PowerShell Prompt"
Add-Content $ProfileFile -Value "function prompt {"
Add-Content $ProfileFile -Value "`$msg = `"HTDOM `$(`$ExecutionContext.SessionState.Path.CurrentLocation)`$(`'>`' * (`$NestedPromptLevel + 1))`""
Add-Content $ProfileFile -Value "Write-Host -ForegroundColor Yellow -NoNewLine `$msg; `" `""
Add-Content $ProfileFile -Value "`}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Setzt bestimmte Alias und Funktionen"
Add-Content $ProfileFile -Value "function pss{Set-Location -Path $StartFolder}"
Add-Content $ProfileFile -Value "function c{Set-Location -Path C:\}"
Add-Content $ProfileFile -Value "function d{Set-Location -Path D:\}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function ..{cd ..}"
Add-Content $ProfileFile -Value "function ...{cd ..\..}"
Add-Content $ProfileFile -Value "function ....{cd ..\..\..}"
Add-Content $ProfileFile -Value "function .....{cd ..\..\..\..}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function ws{Set-Location -Path C:\Windows\System32}"
Add-Content $ProfileFile -Value "function npp{notepad `$PROFILE.CurrentUserAllHosts}"
Add-Content $ProfileFile -Value "function np{Start-Process -FilePath `"C:\Program Files (x86)\Notepad++\notepad++.exe`" -Verb RunAs}"
Add-Content $ProfileFile -Value "function ise{Start-Process -FilePath `"C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe`" -Verb RunAs}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function kb(`$id){Start-Process -FilePath `"http://support.microsoft.com/kb/`$id`"}"
Add-Content $ProfileFile -Value "function mwst(`$betrag, `$satz = 19) {`$betrag / 100 * `$satz}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function applog{Get-EventLog -LogName Application -Newest 50}"
Add-Content $ProfileFile -Value "function syslog {Get-EventLog -LogName System -Newest 50}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function gco(`$Cmdlet){Get-Command `$Cmdlet -CommandType Cmdlet}"
Add-Content $ProfileFile -Value "function about{Get-Help about_* | Select name, synopsis | Format-Table -AutoSize}"
Add-Content $ProfileFile -Value "function module{Get-Module -ListAvailable | Where-Object {`$_.Path -like `"`$PSHOME*`"}}"
#######################################################################################

## Profil in der aktuellen Sitzung laden
. $PROFILE.CurrentUserAllHosts
#######################################################################################

## Erstelle Regkeys für HKEY_CURRENT_USER\Console
$RegPath1="HKCU:\Console"
Set-Location -Path $RegPath1

## Konsolenfarben setzen
New-ItemProperty . ColorTable00 -type DWORD -value 0x00222827 -Force
New-ItemProperty . ColorTable03 -type DWORD -value 0x00141817 -Force
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f2f8f8 -Force
New-ItemProperty . ColorTable09 -type DWORD -value 0x00efd966 -Force
New-ItemProperty . ColorTable10 -type DWORD -value 0x002ee2a6 -Force
New-ItemProperty . ColorTable12 -type DWORD -value 0x007226f9 -Force
New-ItemProperty . ColorTable14 -type DWORD -value 0x0074dbe6 -Force

## Schriftart und zusätzlich Optionen setzen
New-ItemProperty . CurrentPage -type DWORD -value 0x00000003 -Force
New-ItemProperty . CursorSize -type DWORD -value 0x00000019 -Force
New-ItemProperty . EnableColorSelection -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKey -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKeyCustom -type DWORD -value 0x00000000 -Force
New-ItemProperty . FaceName -type STRING -value "Consolas" -Force
New-ItemProperty . FontFamily -type DWORD -value 0x00000036 -Force
New-ItemProperty . FontSize -type DWORD -value 0x000e0000 -Force
New-ItemProperty . FontWeight -type DWORD -value 0x00000190 -Force
New-ItemProperty . FullScreen -type DWORD -value 0x00000000 -Force
New-ItemProperty . HistoryBufferSize -type DWORD -value 0x00000032 -Force
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000 -Force
New-ItemProperty . InsertMode -type DWORD -value 0x00000001 -Force
New-ItemProperty . LoadConIme -type DWORD -value 0x00000001 -Force
New-ItemProperty . NumberOfHistoryBuffers -type DWORD -value 0x00000004 -Force
New-ItemProperty . PopupColors -type DWORD -value 0x000000f5 -Force
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001 -Force
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x270f00c8 -Force
New-ItemProperty . ScreenColors -type DWORD -value 0x0000000f -Force
New-ItemProperty . TrimLeadingZeros -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowSize -type DWORD -value 0x003600c8 -Force
New-ItemProperty . WordDelimiters -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowPosition -type DWORD -value 0x003c00dc -Force
#######################################################################################

## Erstelle Regkeys für HKEY_CURRENT_USER\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe
$RegPath2="HKCU:\Console\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe"
$CheckRegKey2 = Test-Path -Path $RegPath2

if ($CheckRegKey2 -eq $true) {
    Clear-Host
    Remove-Item -Path $RegPath2 -Recurse -Force
    Write-Host "`nRegistrieschlüssel ist vorhanden und wird gelöscht!`n" -ForegroundColor Yellow
    New-Item -Path "HKCU:\Console" -Name "%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe" -Force
    Write-Host "`nRegistrieschlüssel ist nicht vorhanden und wird angelegt.`n" -ForegroundColor Green
} else {
    Clear-Host
    New-Item -Path "HKCU:\Console" -Name "%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe" -Force
    Write-Host "`nRegistrieschlüssel ist nicht vorhanden und wird angelegt.`n" -ForegroundColor Green
}

Set-Location -Path $RegPath2

## Konsolenfarben setzen
New-ItemProperty . ColorTable00 -type DWORD -value 0x00222827 -Force
New-ItemProperty . ColorTable03 -type DWORD -value 0x00141817 -Force
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f2f8f8 -Force
New-ItemProperty . ColorTable09 -type DWORD -value 0x00efd966 -Force
New-ItemProperty . ColorTable10 -type DWORD -value 0x002ee2a6 -Force
New-ItemProperty . ColorTable12 -type DWORD -value 0x007226f9 -Force
New-ItemProperty . ColorTable14 -type DWORD -value 0x0074dbe6 -Force

## Schriftart und zusätzlich Optionen setzen
New-ItemProperty . CurrentPage -type DWORD -value 0x00000003 -Force
New-ItemProperty . CursorSize -type DWORD -value 0x00000019 -Force
New-ItemProperty . EnableColorSelection -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKey -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKeyCustom -type DWORD -value 0x00000000 -Force
New-ItemProperty . FaceName -type STRING -value "Consolas" -Force
New-ItemProperty . FontFamily -type DWORD -value 0x00000036 -Force
New-ItemProperty . FontSize -type DWORD -value 0x000e0000 -Force
New-ItemProperty . FontWeight -type DWORD -value 0x00000190 -Force
New-ItemProperty . FullScreen -type DWORD -value 0x00000000 -Force
New-ItemProperty . HistoryBufferSize -type DWORD -value 0x00000032 -Force
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000 -Force
New-ItemProperty . InsertMode -type DWORD -value 0x00000001 -Force
New-ItemProperty . LoadConIme -type DWORD -value 0x00000001 -Force
New-ItemProperty . NumberOfHistoryBuffers -type DWORD -value 0x00000004 -Force
New-ItemProperty . PopupColors -type DWORD -value 0x000000f5 -Force
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001 -Force
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x270f00c8 -Force
New-ItemProperty . ScreenColors -type DWORD -value 0x0000000f -Force
New-ItemProperty . TrimLeadingZeros -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowSize -type DWORD -value 0x003600c8 -Force
New-ItemProperty . WordDelimiters -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowPosition -type DWORD -value 0x003c00dc -Force
#######################################################################################

## Kopiere Regkeys für HKEY_CURRENT_USER\Console\Windows PowerShell
$RegPath3="HKCU:\Console\Windows PowerShell"
$CheckRegKey3 = Test-Path -Path $RegPath3

if ($CheckRegKey3 -eq $true) {
    Clear-Host
    Remove-Item -Path $RegPath3 -Recurse -Force
    Write-Host "`nRegistrieschlüssel ist vorhanden und wird gelöscht!`n" -ForegroundColor Yellow
    New-Item -Path "HKCU:\Console" -Name "Windows PowerShell" -Force
    Write-Host "`nRegistrieschlüssel ist nicht vorhanden und wird angelegt.`n" -ForegroundColor Green
} else {
    Clear-Host
    New-Item -Path "HKCU:\Console" -Name "Windows PowerShell" -Force
    Write-Host "`nRegistrieschlüssel ist nicht vorhanden und wird angelegt.`n" -ForegroundColor Green
}

Set-Location -Path $RegPath3

## Konsolenfarben setzen
New-ItemProperty . ColorTable00 -type DWORD -value 0x00222827 -Force
New-ItemProperty . ColorTable03 -type DWORD -value 0x00141817 -Force
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f2f8f8 -Force
New-ItemProperty . ColorTable09 -type DWORD -value 0x00efd966 -Force
New-ItemProperty . ColorTable10 -type DWORD -value 0x002ee2a6 -Force
New-ItemProperty . ColorTable12 -type DWORD -value 0x007226f9 -Force
New-ItemProperty . ColorTable14 -type DWORD -value 0x0074dbe6 -Force

## Schriftart und zusätzlich Optionen setzen
New-ItemProperty . CurrentPage -type DWORD -value 0x00000003 -Force
New-ItemProperty . CursorSize -type DWORD -value 0x00000019 -Force
New-ItemProperty . EnableColorSelection -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKey -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKeyCustom -type DWORD -value 0x00000000 -Force
New-ItemProperty . FaceName -type STRING -value "Consolas" -Force
New-ItemProperty . FontFamily -type DWORD -value 0x00000036 -Force
New-ItemProperty . FontSize -type DWORD -value 0x000e0000 -Force
New-ItemProperty . FontWeight -type DWORD -value 0x00000190 -Force
New-ItemProperty . FullScreen -type DWORD -value 0x00000000 -Force
New-ItemProperty . HistoryBufferSize -type DWORD -value 0x00000032 -Force
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000 -Force
New-ItemProperty . InsertMode -type DWORD -value 0x00000001 -Force
New-ItemProperty . LoadConIme -type DWORD -value 0x00000001 -Force
New-ItemProperty . NumberOfHistoryBuffers -type DWORD -value 0x00000004 -Force
New-ItemProperty . PopupColors -type DWORD -value 0x000000f5 -Force
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001 -Force
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x270f00c8 -Force
New-ItemProperty . ScreenColors -type DWORD -value 0x0000000f -Force
New-ItemProperty . TrimLeadingZeros -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowSize -type DWORD -value 0x003600c8 -Force
New-ItemProperty . WordDelimiters -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowPosition -type DWORD -value 0x003c00dc -Force
#######################################################################################

## Powershell Verknüpfung erstellen
$ComObj = New-Object -ComObject Wscript.Shell
$Shortcut = $ComObj.CreateShortcut("$env:USERPROFILE\Desktop\Powershell.lnk")
$ShortCut.TargetPath = "$PSHOME\powershell.exe"
$ShortCut.Hotkey = "CTRL+ALT+P"
$ShortCut.Save()
####################################################################################### 

Wie immer freue ich mich über Kommentare und Anregungen.

Viele Grüße
Helmut

Seit 1. September ist die neue Sysinternals Suite verfügbar. Mit diesen kleinen Tools ist es möglich PC’s Remote im Netzwerk zu verwalten und zu administrieren. Mark Russinovich hat so zusagen alle Tools die man früher einzeln downloaden konnte in eine Suite zusammengefasst. Die bekanntesten Tools sind wohl die PSTools, BGInfo, Process Explorer und der TCPViewer.

Hier eine Auflistung aller Tools in der Suite –> http://technet.microsoft.com/de-de/sysinternals/bb545027

Und hier ein paar Beispiele was man mit den Tools so alles anstellen kann.

Man erstellt sich eine host.csv oder host.txt Datei die ungefähr so aussieht.

image

Und kann dann mit Batch Dateien sein Netzwerk bzw. seine Clients nach bestimmten Informationen abfragen.

psinfo.exe (Hier hole ich mir die Festplatteninformation welche Software & Hotfixe installiert sind)

@echo off
set host=host.txt
if not exist „C:\PCLogs\psinfo“ mkdir „C:\PCLogs\psinfo“
for /f %%i in (%host%) do „%systemroot%\system32\psinfo.exe“ -d -s -h \\%%i > „C:\PCLogs\psinfo\%%i.txt“

pslist.exe (Prozesse anzeigen lassen)

@echo off
set host=host.txt
if not exist „C:\PCLogs\pslist“ mkdir „C:\PCLogs\pslist“
for /f %%i in (%host%) do „%systemroot%\system32\pslist.exe“ –m oder -t \\%%i > „C:\PCLogs\pslist\%%i.txt“

psexec.exe (Hier kann ich mir bestimmte Informationen Remote anzeigen lassen)

@echo off
set host=host.txt
if not exist „C:\PCLogs\psexec“ mkdir „C:\PCLogs\psexec“
for /f %%i in (%host%) do „%systemroot%\system32\psexec.exe“ \\%%i systeminfo > „C:\PCLogs\psexec\%%i.txt“

oder ich führe den Befehl auf jeden PC einzeln aus um schnell an Informationen zu gelagen.

psexec \\computername cmd [Enter] führe dann auf der Remote Console meine Befehle aus systeminfo oder ipconfig /all oder set.

psloglist.exe (Hier kann ich Remote auf die Ereignissprotokolle der Clients zugreifen und abfragen)

@echo off
set host=host.txt
if not exist „C:\PCLogs\psloglist“ mkdir „C:\PCLogs\psloglist“
for /f %%i in (%host%) do „%systemroot%\system32\psloglist.exe“ \\%%i -s -r -i 3 -h 48 Application > „C:\PCLogs\psloglist\%%i_application.txt“
for /f %%i in (%host%) do „%systemroot%\system32\psloglist.exe“ \\%%i -s -r -i 534 -d 30 Security > „C:\PCLogs\psloglist\%%i_security.txt“
for /f %%i in (%host%) do „%systemroot%\system32\psloglist.exe“ \\%%i -s -r -i 29 -h 48 System > „C:\PCLogs\psloglist\%%i_system.txt“

Hier noch ein paar nützliche Befehle:

Benutzer abmelden: psshutdown -f -o \\computername

PC neu starten: psshutdown -r -t 5 \\computername

Prozesse beenden: pslist \\computername –> pskill \\computername -t Prozessname oder Prozess ID

Wer ist am System angemeldet: psloggedon –l \\computername

Dienste Remote starten/beenden/neu starten: psservice \\computername start/stop/restart “Servicename”

Dienste Remote suchen: psservice \\computername query “ser”

Computer SID herausfinden: psgetsid \\computername

Mit  sDelete steht dem Administrator ein Tool zur Verfügung um sicher Daten zu löschen bzw. Datenträger zu bereinigen:

Sicheres Löschen: sdelete –p 3 –s “C:\Users\<username>\AppData\Local\Mozilla\Firefox\Profiles\2xcds7cer.default\Cache”

Datenträger bereinigen: sdelete –p 3 –z C: oder sdelete –p 3 –z –c C:

Der Process Explorer ist ein toller Ersatz für den Windows XP/7 Task Manger (Über Options –> Replace Task Manager, kann man den Process Explorer als Default Task Manager definieren)

image

Der TCPViewer hat mir auch schon sehr nützliche Dienste geleistet

image

Mit Rammap kann man sich den physikalischen Arbeitsspeicher von Windows anzeigen lassen, sehr Interessant.

image

Viel Spaß beim administrieren und ausprobieren.

Viele Grüße
Helmut

Anders als seine Vorgänger bietet Windows Server 2008 ohne zusätzliche Tools die Möglichkeit, Snapshots von ganzen Laufwerken durch die Verwendung der Volume-Shadow Copy-Services (VSS) auf einfache Weise zu nutzen. So lassen sich Backups und andere Sicherungen auch mit Dateien durchführen, die durch den Zugriff von Benutzern gesperrt sind.

Um ein Laufwerk oder Teile davon zu sichern, kann wie folgt vorgegangen werden: Zunächst wird der Kommandozeilenbefehl “Diskshadow” aufgerufen. Danach werden nacheinander folgende Befehle eingegeben:

Set Context Persistent Nowriters
– Begin Backup
– Add Volume C: Alias C_Shadow
– Create
– Expose %C_Shadow% P:
Exec C:\Windows\System32\cmd.exe

Nun befindet man sich wieder auf der Windows-Kommandozeile und hat ein schreibgeschütztes Laufwerk P:, das eine exakte Kopie des Laufwerks C: zum Zeitpunkt der Eingabe des Create-Befehls ist. Das neue Laufwerk P: oder Teile davon können nun nach Belieben genutzt werden, beispielsweise mit Robocopy. Alle Dateien haben einen konsistenten Zustand und sind nicht durch andere Benutzer gesperrt.

Anschließend kehrt man mit dem Befehl “Exit 0″ zurück in die Diskshadow-Shell. Dort gibt man folgende Befehle ein:

End Backup
– Delete Shadows Id %C_Shadow%
Exit

Damit wird die Schattenkopie wieder gelöscht und der benötigte Platz freigegeben. Eine detaillierte Beschreibung des sehr mächtigen Diskshadow-Tools findet sich auf Microsoft Technet