Automatisierung mit Windows PowerShell V1 / V2 3/28/2017 1:11 PM Automatisierung mit Windows PowerShell V1 / V2 Ralf Feest Director Enterprise Services AddOn (Schweiz) AG, Zürich © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Meine Ziele für diesen Vortrag PowerShell-Anfänger abholen & begeistern PowerShell-Nutzern Tipps & Tricks sowie einen Ausblick auf die V 2.0 zeigen Den richtigen Mix aus Theorie & LiveDemo präsentieren
Einführung in PowerShell Erweiterung der bekannten cmd.exe unterstützt/integriert das .NET Objektmodell Schnittstellen zu .NET Framework ADSI WMI XML
Voraussetzungen der V 1.0 .NET Framework 2.0 Unterstützte Betriebssysteme Einstieg mit Webcasts, Doku etc. unter www.addon-ag.ch?ad1033 Windows XP Service Pack 2 Windows Server 2003 Service Pack 1 Windows Vista Windows Server 2008 Installation via Servermanager als „Feature“ Keine Unterstützung innerhalb von ServerCore vor Erscheinen von R2!
Pipe-Symbol zum objektorientierten (!) Verketten zweier cmdlets Aufbau eines cmdlet cmdlet (sprich: „commandlet“) = Befehl, der nur innerhalb einer PS ausgeführt werden kann Beispiel: get-Process | select-Object Name,StartTime Verb Subjekt Auswahl Attribute Pipe-Symbol zum objektorientierten (!) Verketten zweier cmdlets
Wo bekomme ich Hilfe? Übersicht der cmdlets: get-command Liste der Kurzkommandos (Alias): get-alias z. B. ps steht für Get-Process oder dir steht für Get-Childitem Syntax eines Befehls abrufen: get-help get-process get-help get-process -detailed get-help get-process -full
Erste Schritte mit der PowerShell demo
PowerShell Beispiele (1) Welche Datei-Endungen kommen wie häufig in einer Verzeichnisstruktur vor? Get-ChildItem -recurse | group-object extension | sort -property Count -descending
PowerShell Beispiele (2) Zugriff auf die Registry Wert aus der Registry abfragen get-itemproperty -path "HKCU:\Software\AddOn\Snake“ -name Highscore Wert in der Registry neu setzen set-itemproperty -path "HKCU:\Software\AddOn\Snake“ -name Highscore –value 1740
PSdrives demo
Neue AD-Schnittstelle ab W2008 R2 Erweiterung für die PowerShell Import-Module ActiveDirectory Voraussetzungen mind. ein Windows 2008 R2 DC .NET Framework 3.5.1 Client: W2008 R2 oder Windows 7
Ein PSdrive für das AD
Mit cd durch's AD browsen…
>70 neue AD-cmdlets Add-ADComputerServiceAccount Get-ADUser Set-ADAccountExpiration Add-ADDomainControllerPasswordReplicationPolicy Get-ADUserResultantPasswordPolicy Set-ADAccountPassword Add-ADFineGrainedPasswordPolicySubject Install-ADServiceAccount Set-ADComputer Add-ADGroupMember Move-ADDirectoryServer Set-ADDefaultDomainPasswordPolicy Add-ADPrincipalGroupMembership Move-ADDirectoryServerOperationMasterRole Set-ADDomain Clear-ADAccountExpiration Move-ADObject Set-ADDomainMode Disable-ADAccount New-ADComputer Set-ADFineGrainedPasswordPolicy Disable-ADOptionalFeature New-ADFineGrainedPasswordPolicy Set-ADForest Enable-ADAccount New-ADGroup Set-ADForestMode Enable-ADOptionalFeature New-ADObject Set-ADGroup Get-ADAccountAuthorizationGroup New-ADOrganizationalUnit Set-ADObject Get-ADAccountResultantPasswordReplicationPolicy New-ADServiceAccount Set-ADOrganizationalUnit Get-ADComputer New-ADUser Set-ADServiceAccount Get-ADComputerServiceAccount Remove-ADComputer Set-ADUser Get-ADDefaultDomainPasswordPolicy Remove-ADComputerServiceAccount Uninstall-ADServiceAccount Get-ADDomain Remove-ADDomainControllerPasswordReplicationPolicy Unlock-ADAccount Get-ADDomainController Remove-ADFineGrainedPasswordPolicy Get-ADDomainControllerPasswordReplicationPolicy Remove-ADFineGrainedPasswordPolicySubject Get-ADDomainControllerPasswordReplicationPolicyUsage Remove-ADGroup Get-ADFineGrainedPasswordPolicy Remove-ADGroupMember Get-ADFineGrainedPasswordPolicySubject Remove-ADObject Get-ADForest Remove-ADOrganizationalUnit Get-ADGroup Remove-ADPrincipalGroupMembership Get-ADGroupMember Remove-ADServiceAccount Get-ADObject Remove-ADUser Get-ADOptionalFeature Rename-ADObject Get-ADOrganizationalUnit Reset-ADServiceAccountPassword Get-ADPrincipalGroupMembership Restore-ADObject Get-ADRootDSE Search-ADAccount Get-ADServiceAccount Set-ADAccountControl
Eigene PSdrive Provider Kennen Sie noch den subst-Befehl? New-PSDrive -name X –psprovider FileSystem -root c:\scripts New-PSDrive -name Y -psprovider Registry -root HKCU:\Software\Microsoft\Windows\CurrentVersion SQL Server 2008 mit eigenem PSdrive cd SQLSERVER:\SQL\localhost\DEFAULT\Databases\Sales\Tables Get-ChildItem | where {$_.Schema -eq "Sales"} 3rd Party Provider downloadbar MSDN-Artikel "Creating a Windows PowerShell Drive Provider"
Zugriff auf Ereignisprotokoll Welche Ereignislogs gibt es? get-eventlog –list Ereignisliste eines bestimmten Log abfragen: get-eventlog –LogName Application Die fünf jüngsten Einträge abrufen: get-eventlog –LogName Application –newest 5 Alle Attribute eines einzelnen Eintrags abrufen: get-eventlog -LogName Application | where-object {$_.index -eq 17015} | select-object *
Formatierung der Ausgabe Ausgabe als Liste format-list (Objekte einzeln untereinander) Ausgabe in Tabelle format-table Ausgabe in eine Datei CSV Get-ChildItem Brief.pdf | export-csv -path test.csv XML Get-ChildItem Brief.pdf | export-Clixml -path test.xml
Befehle mitschneiden Protokollierung start-transcript –path <Datei> stop-transcript Ausgabe einer Datei auf dem Bildschirm type log.txt get-content log.txt Druckausgabe an den Standarddrucker out-printer –name <Datei> an einen bestimmten Netzwerkdrucker out-printer -name "\\Server01\Prt-6B Color"
Skripte erstellen und ausführen Default: Nur signierte PowerShell Skripte dürfen ausgeführt werden! Ausführungsrichtlinie abfragen: Get-ExecutionPolicy setzen: Set-ExecutionPolicy -ExecutionPolicy unrestricted (einmal durch Administrator) Skript aufrufen: Die Datei "C:\Users\rfeest\Desktop\ralf.ps1" kann nicht geladen werden, da die Ausführung von Skripts auf diesem System deaktiviert ist.
Variablen (1) eingebaute Variablen Eigene Variablen z. B. $PWD, $HOME, $PROFILE etc. Liste abfragbar mit dir variable: | sort name Umgebungsvariablen mit dir env: | sort name Eigene Variablen Keine Deklaration notwendig, einfach verwenden $netto= 270 $brutto= $netto * 1.075 "Der Rechnungsbetrag beträgt $brutto CHF."
Variablen (2) Alternative: Variable mit New-Variable anlegen: new-Variable Mehrwertsteuer 0.19 –option ReadOnly Typ der Variablen abfragen: $Mehrwertsteuer.GetType() $Mehrwertsteuer.GetType().Name ohne Dollarzeichen! Zusatzoptionen Wertzuweisung
Schleifen Beispiel: Quadratzahlen 1, 4, 9, 16, … 100 while(expression) { … } do { … } until/while(expression) Beispiel: Quadratzahlen 1, 4, 9, 16, … 100 for([initializer];[condition];[iterator]{…} foreach-object(identifier in collection){…} #Skript zur Berechnung von Quadratzahlen $Quadrat=1 while ($Quadrat -le 10) { write-host ($Quadrat * $Quadrat) $Quadrat +=1 }
IE fernsteuern demo 1. $ie= new-object -com "InternetExplorer.Application" 2. $ie.Visible= $true 3. $ie.navigate("http://www.denver.com") 4. $ie |get-member 5. $ie.StatusText 6. $ie.document | get-member 7. $ie.document.title 8. $ie.document.documentElement.innerHTML 9. $ie.document.documentElement.innertext 10. $ie.document.documentElement.innertext.indexOf("IIS") 11. $ie.document.documentElement.innertext.substring(110,7) 12. $ie.quit()
WMI und Office Zugriff per WMI get-Wmiobject -class Win32_LogicalDisk | ft Name,VolumeName,Size,FreeSpace Zugriff auf Office-Applikationen Beispiel: Anzahl Mails im Posteingang und Auflisten der Absender aller Mails $Outlook= new-object -comobject Outlook.Application $Posteingang= $Outlook.Session.GetDefaultFolder(6) write-host $Posteingang.Items.Count foreach ($Mail in $Posteingang.Items) {$Mail.SenderName}
ADSI Abfragen der Beschreibung eines Benutzers $u.description $u= [ADSI]”LDAP://cn=Ralf Feest,ou=Training,dc=denver,dc=com” Abfragen der Beschreibung eines Benutzers $u.description Ändern der Telefonnummer eines Benutzers $u.TelephoneNumber= “+41 17 4897-11“ $u.SetInfo() Auflisten aller Computerkonten der Domäne $ad=[ADSI]"LDAP://dc=denver,dc=com“ $ds= new-object System.DirectoryServices.DirectorySearcher $ds.SearchRoot= $ad $ds.Filter="(objectCategory=computer)" $Ergebnisse= $ds.FindAll() foreach ($PC in $Ergebnisse) {write-host $PC.Properties.name} .Net Framework
Unterstützung für XML $MA = [xml]"<Mitarbeiter> <Person> <Name>Meier</Name> <Tel>(0123)4567</Tel> </Person> <Name>Schuster</Name> <Tel>(0987)6543</Tel> </Mitarbeiter>" write-host $MA.Mitarbeiter.Person[1].Name write-host $MA.Mitarbeiter.Person[1].Tel
Exchange Administration Exchange 2007 Administration per PowerShell nur auf dem Exchange Server direkt per RDP-Session remote Exchange-Remote-Admin z. B. von VISTA aus: PowerShell V1 installieren Exchange 2007 Administrationstools installieren
Exchange 2007 Benutzer mit Postfach anlegen $maildb= get-mailboxDatabase $pwd= convertto-securestring -string ".ServerSummit2008" -asplaintext -force new-mailbox -name "Hans Dampf" -alias hdampf -organizationalUnit "contoso.com/Training" -userPrincipalName hdampf@contoso.com -samAccountName hdampf -FirstName Hans -LastName Dampf -password $pwd -ResetPasswordOnNextLogon $false -Database $maildb
Remote Administration mit V1 Remote Admin via WMI Beispiel: SystemDirectory : C:\Windows\system32 Organization : BuildNumber : 6001 RegisteredUser : Ralf SerialNumber : 89587-014-3171252-71989 Version : 6.0.6001 SystemDirectory : C:\WINDOWS\system32 Organization : AddOn BuildNumber : 3790 RegisteredUser : AddOn SerialNumber : 69713-286-0895857-44217 Version : 5.2.3790 Organization : addon RegisteredUser : ctec SerialNumber : 69713-640-1693711-45097 $PCs= $("BBN25", "BBS12", "BBS5") Get-WmiObject Win32_OperatingSystem -computer $PCs
PowerShell V2 Momentan Beta-/CTP-Status*), connect.microsoft.com XP SP3 Win Server 2003 SP2 Vista SP1 Windows 2008 Windows 2008 R2 Windows 7 V2 included PowerShell V2 Momentan Beta-/CTP-Status*), connect.microsoft.com installierbar auf ca. 60 neue cmdlets Bessere Unterstützung für remote Administration Windows Management Instrumentation (WMI) Windows Remote Management (WinRM) built-in bei Vista SP1 und Windows 2008, Download für Windows 2003 und XP (in CTP noch nicht unterstützt) Abfrage von mehreren Systemen oder Ausführung mehrere Aufgaben können mit Hilfe von Background Threads parallelisiert werden! grafische Entwicklungsoberfläche *) Community Technology Preview
verschlüsselter Datentransfer WS-Management Protocol Remote PowerShell in V2 verschlüsselter Datentransfer WS-Management Protocol Invoke-Command –computername FileSrv02 –scriptblock {get-process} technische Voraussetzungen: WinRM Dienst muss laufen Enable-PSremoting muss einmal aufgerufen werden Noch keine Unterstützung für Windows 2003 und Vista bisher (könnte aber kommen)
RunSpaces in V2 Mit RunSpaces (jetzt: PSsessions) können PowerShell cmdlets auf remote Computer initiiert werden temporärer RunSpace: Persistenter RunSpace: Invoke-Command –computername DC –scriptblock {ps winlogon} $dc= New-PSsession –Computername DC –Credential rfeest@contoso.com Invoke-Command –session $dc –scriptblock {ps winlogon} Invoke-Command –session $dc –scriptblock {get-Psdrive} get-PSsession remove-PSsession –session $dc
PowerShell V2 – Background Prozesse Start-job -scriptblock {get-process} führt die Kommandos im Hintergrund aus Prompt kommt sofort zurück Get-Job zeigt eine Übersicht der Background-Prozesse an Gezielte Stausabfrage eines Prozesses möglich Wait-Job –id <JobID> gibt einen Prompt zurück, wenn Job fertig Receive-Job –id <JobID> ermittelt die Ergebnisse der Background-Prozesse
Die PowerShell ISE
PowerShell V 2.0 demo
Your MSDN resources check out these websites, blogs & more! 3/28/2017 1:11 PM Your MSDN resources check out these websites, blogs & more! Presentations TechDays: www.techdays.ch MSDN Events: http://www.microsoft.com/switzerland/msdn/de/presentationfinder.mspx MSDN Webcasts: http://www.microsoft.com/switzerland/msdn/de/finder/default.mspx MSDN Events MSDN Events: http://www.microsoft.com/switzerland/msdn/de/events/default.mspx Save the date: Tech•Ed 2009 Europe, 9-13 November 2009, Berlin MSDN Flash (our by weekly newsletter) Subscribe: http://www.microsoft.com/switzerland/msdn/de/flash.mspx MSDN Team Blog RSS: http://blogs.msdn.com/swiss_dpe_team/Default.aspx Developer User Groups & Communities Mobile Devices: http://www.pocketpc.ch/ Microsoft Solutions User Group Switzerland: www.msugs.ch .NET Managed User Group of Switzerland: www.dotmugs.ch FoxPro User Group Switzerland: www.fugs.ch © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Your TechNet resources check out these websites, blogs & more! 3/28/2017 1:11 PM Your TechNet resources check out these websites, blogs & more! Presentations TechDays: www.techdays.ch TechNet Events TechNet Events: http://technet.microsoft.com/de-ch/bb291010.aspx Save the date: Tech•Ed 2009 Europe, 9-13 November 2009, Berlin TechNet Flash (our by weekly newsletter) Subscribe: http://technet.microsoft.com/de-ch/bb898852.aspx Schweizer IT Professional und TechNet Blog RSS: http://blogs.technet.com/chitpro-de/ IT Professional User Groups & Communities SwissITPro User Group: www.swissitpro.ch NT Anwendergruppe Schweiz: www.nt-ag.ch PASS (Professional Association for SQL Server): www.sqlpass.ch © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Save the date for tech·days next year! 3/28/2017 1:11 PM Save the date for tech·days next year! 7. – 8. April 2010 Congress Center Basel © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Premium Sponsoring Partners 3/28/2017 1:11 PM Premium Sponsoring Partners Classic Sponsoring Partners Media Partner © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
3/28/2017 1:11 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.