ICT dag 03/12 Managing Systems with PowerShell Bart Portier docent TW KHK Geel Microsoft Certified Trainer
What is PowerShell? Comparing applications and scripts in Vista Learning PowerShell Automating with PowerShell Exercise : filesystem management with PowerShell
Deel 1 : UAC en soorten scripts
Scripting applications vista : stand van zaken Vergelijking VBS BAT PS1 User Account control : verband tussen UAC en scripts
Wat is UAC? User Account Control
Meer controle, zonder Administrator te zijn!
Script alternatieven.bat.vbs.ps1 Works? Limited Limited After install of powershell (hotfix) Script elevation? Usage? Remote? No, unless powertoys Logon script Startup script No, unless powertoys Logon script Startup script Yes and no Batch management
issues Script issues Startup script om numlock aan te zetten doet het niet Vbs startup scripts worden via policies vaak via vertraging uitgevoerd, en hebben een 2de reboot nodig Policy and profile issues Logonscripts werkten wel en niet tussen de verschillende beta versies van Vista Script om locale user profiles te verwijderen worden niet meer gesupporteerd. (demo) Moveuser.exe not supported (http://support.microsoft.com/k b/930955/en-us) GPO en beperkte backward compatibility
Demo: moveuser.exe Install hotfix (KB) After you install the update that is described in this article, the User Profile Windows Management Instrumentation (WMI) provider (Win32_UserProfile) is added in Windows Vista. This User Profile WMI provider replaces Moveuser.exe in Windows Vista. The new User Profile WMI provider can be used to map an existing local account profile to a new domain based account. It can also be used to map an existing domain-based account profile to a new domain-based account profile.
Vervolg: moveuser.exe Show profiles in profile directory (all folder options switched to full visibility) Run script : listing profiles Run script : deleting profiles
Locale profielen Traditionele aanpak Resource kit tool: moveuser.exe Deletes caches user profiles during boot vista WMI addition: win32_userprofile Zie : wmicodecreator (demo)
Elevating scripts there is the Elevate Command PowerToy which can get the job done. It was written by Michael Murgolo, a consultant with Microsoft Consulting Services The tool is discussed here: http://www.microsoft.com/technet/technetmag/issues/2 007/06/UtilitySpotlight/default.aspx. And is available for download here: http://www.technetmagazine.com/code07.aspx Vb : elevate notepad c:\windows\win.ini Vb : elevate wscript C:\windows\system32\ slmgr.vbs dli
Powertoys : elevate scripts Vb : elevate.cmd wscript c:\users\admin\deletevistaprofile.vbs
Voetnoot: slmgr.vbs slmgr.vbs [MachineName [User Password]] [<Option>] MachineName: Name of remote machine (default is local machine) User: Account with required privilege on remote machine Password: password for the previous account Global Options -ipk <product key> Install product key (replaces existing key) -upk Uninstall product key -ato Activate Windows -dli [Activation ID All] Display license information (default: current license) -dlv [Activation ID All] Display detailed license information (default: current license) -xpr Expiration date for current license state
Profile errors http://support.microsoft.com/kb/934907/en-us http://support.microsoft.com/kb/921468/en-us http://support.microsoft.com/kb/940453/en-us
Deel 2 : Wat is powershell?
Windows PowerShell New command-line shell and scripting language interactive (vb. Tab completion) programmatic (vb. Verb-noun construct) production oriented (vb. Exchange 2007) Allows access to data stores as easy to access as filesystem
The Difference is OBJECTS! Get-Process Where { $_.handles gt 500 } Sort handles Format-Table Common Windows PowerShell Parser Format Cmdlet Sort Cmdlet Where Cmdlet Get-Process Cmdlet Windows PowerShell Pipeline Processor
Mailbox Statistics Database Mgmt Recipient Mgmt Exchange 2003 (VBScript) Set listexchange_mailboxs = GetObject("winmgmts:{impersonationLevel=impersonate}!\\COMPUTERNAME\ROOT\MicrosoftExchangeV2"). InstancesOf("Exchange_Mailbox") For Each objexchange_mailbox in listexchange_mailboxs WScript.echo "AssocContentCount = + objexchange_mailbox.assoccontentcount WScript.echo " DateDiscoveredAbsentInDS = + objexchange_mailbox.datediscoveredabsentinds WScript.echo " DeletedMessageSizeExtended = + objexchange_mailbox. DeletedMessageSizeExtended WScript.echo " LastLoggedOnUserAccount = + objexchange_mailbox. LastLoggedOnUserAccount WScript.echo " LastLogoffTime = + objexchange_mailbox. LastLogoffTime WScript.echo " LastLogonTime = + objexchange_mailbox. LastLogonTime WScript.echo " LegacyDN = + objexchange_mailbox. LegacyDN WScript.echo " MailboxDisplayName = + objexchange_mailbox. MailboxDisplayName WScript.echo " MailboxGUID = + objexchange_mailbox. MailboxGUID WScript.echo " ServerName = + objexchange_mailbox. ServerName WScript.echo " Size = + objexchange_mailbox. Size WScript.echo " StorageGroupName = + objexchange_mailbox. StorageGroupName WScript.echo " StorageLimitInfo = + objexchange_mailbox. StorageLimitInfo WScript.echo " StoreName = + objexchange_mailbox. StoreName WScript.echo " TotalItems = + objexchange_mailbox. TotalItems Next Dim StorGroup as New CDOEXM.StorageGroup StorGroup.DataSource.Open "LDAP://" + DCServer + "/ CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration," + DomainName StorGroup.MoveLogFiles("C:\newlogPath", 0) Dim objmailbox As CDOEXM.IMailboxStore Set objmailbox = GetObject("LDAP://" + DCServer + "CN=FOO,CN=users," + DomainName) objmailbox.createmailbox "LDAP://" + DCServer + "/CN=Private MDB,CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration," + DomainName E12 (Monad Script) get-mailboxstatistics server $servername move-storagegrouppath -identity First Storage Group log "C:\newlogPath enable-mailbox -identity domain\foo database First Storage Group\Private MDB
Install powershell, run basic commands DEMO: SHORT INTRODUCTION TO POWERSHELL
Exploring commands GET commands get-command get-* Get-command get-* more Get-command group-object verb Get-command group-object noun Get-command group-object noun sort-object name GET = verb, NOUN = command SET = verb, NOUN =. Get-command *-process Get-command *-service Get-help get-process (or) get-process -? Get-help get-process more (or) get-process -? more Get-date >c:\write.txt
Pipeline commands GET-process svchost sort-object processname format-table processname, handlecount Get-process Sort-object Format-table
cmdlets V 1.0 : more than 100 cmdlets. Let s count them: $a = get-command $a.count $(get-command).count Get-command group-object noun Get-command group-object noun sort-object name
Writing cmdlets or scripts GET commands $a = get-process $b = get-date $c = process count: + $a.count + at + $b.tostring() Write-host $c Set-content c:\store.txt $c Get-content c:\content.txt You can run this in the power shell You can copy the code to notepad and save it as script1.ps1 How to run the script? Go to the folder with the script Type :.\script1.ps1 Or from start > run : type : powershell.exe c:\folder\script1.ps1 Watch out! Set-executionPolicy must allow execution of scripts Tip: start-transcript, stop-transcript
Ps1 scripts starten Powershell.exe c:\path\script.ps1 Error: PS C:\Users\leonard> Set-ExecutionPolicy unrestricted Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\ 1\ShellIds\Microsoft.PowerShell' is denied. At line:1 char:20 + Set-ExecutionPolicy <<<< unrestricted Oorzaak: UAC + ExecutionPolicy Set-executionPolicy
Werkwijze : set-executionpolicy executionpolicy unrestricted Create shortcut to : powershell.exe This behavior is by design. As a policy, ExecutionPolicy is designed so that only administrators can modify it. PowerShell users on XP and Windows Server 2003 likely didn't see this as most users login with administrative privileges. In Vista, this changed with the advent of User Account Control. Unless explictly requested, processes started by an Administrator account will run as a standard user and not Administrator. You can do this most easily by right-clicking the PowerShell icon in the Start Menu and selecting "Run as Administrator".
Deel 3 :PowerShell and.net Using.net from the powershell Extending PS with.net classes Extending PS with WMI
example $now = [system.datetime]::get_now() $now.year $now.dayofweek $now get-member more Compare to what you do in WebDeveloper and Vbscript (WSH).net Imports WSH - createobject
Extending with WMI Get-wmiObject Get-WmiObject Namespace root\cimv2 class win32_currenttime Oefening: get-wmiobject win32_userprofile Get-wmiObject win32_userprofile get-member Look for the Delete-method
whatif Remove-item c:\deleteme\t*.txt -whatif
Filesystem example Get-childItem Path c:\windows\system32 filter *.dll Where-object {$_.creationtime.year eq 2006 } Sort-object creationtime Format-Table name, creationtime
COM scripting $ie = new-object comobject InternetExplorer.Application $ie.visible = $true $ie.navigate2(http://www.primalscript.com)
Filter example Get-service where-object { $_.status eq running and $._name match sql } Other operators -lt (less than) -gt (greater than) -le (less and equal) -ne (not equal) - contains, -notcontains
Get-help get-service parameter *
Oefening : stop de telnet service Wat wil je doen? Installeer Telnet server en zet startup type op manual Roep lijst services op Roep info op over commando s met service in naam Roep info over stopservice op Stop de service. Commands??????
Oefening : stop de telnet service Wat wil je doen? Installeer Telnet server en zet startup type op manual Roep lijst services op Roep info op over commando s met service in naam Roep info over stopservice op Stop de service. Commands? Get-service Get-command *service Get-help stop-service parameter * Stop-service tlnt*
compare cmd Dir *.txt cmdlet Get-childItem *.txt Provider: alias Set-location alias: Get-childitem d* Get-childitem l* Provider: HKCU Set-location HKCU: Get-childitem Get-childitem l* Return: Set-location path c:\
Transformation and Output Commands Format -Custom -List -Table -Wide Out -File -Host -Printer -String Export/Import -CliXML -CSV ConvertTo -HTML Functions Convert objects into formatting records Convert formatting records into output-specific directives. Converts objects into and out of file formats Converts object into other objects
examples Get-service format-table name, status Get-service select-object name, status group-object status Get-service where-object {$_.status eq running } Gsv? {$_.status eq running }
Output en input DEMO: TRANSFORMATION AND OUTPUT UTILITIES
POWERSHELL V2 COMMUNITY TECHNOLOGY PREVIEW (CTP)
Availability /Applicability The PowerShell V2 CTP is not for everyone Read this PowerShell Team blog entry: http://blogs.msdn.com/powershell/archive/2007/11/02/ctpwatch-this-space.aspx
PowerShell V2 Themes Universal Code Execution Model GUI over PowerShell Production Scripting Community Feedback
PowerShell V2 Themes Commands, expressions and ScriptBlocks can be run in the foreground or background on one or more machines over a LAN or a WAN in unrestricted or restricted environments using short or long connections using impersonation or supplied credentials initiated by user input or by events Universal Code Execution Model
Features Remoting Mobile Object Model Background Jobs Restricted Runspaces Eventing (coming soon) Universal Code Execution Model
Features New hosting APIs Runspace pooling GUI over PowerShell
Features Graphical PowerShell Script Cmdlets Script Internationalization/Data Language Debugging Packages and modules (coming soon) Production Scripting
Features Language enhancements Improved adapters New/improved cmdlets Community Feedback
Call To Action Download PowerShell CTP On non-production systems Kick the tires and let us know what we got right/wrong Let us know about any incompatibilities with V1
Invest and learn how to: Learn and leverage others work Discover the system Leverage utilities Formalize your work Methods apply to V1 and V2
In the box documents Release Notes Getting Started, Users Guide, Quick Reference Guide Help Discovery utilities Books Community Practice ad hoc development
Utilities - Discovery Command Get-Help Get-Command Get-Member Get-PSDrive Function Help about PowerShell commands and topics Get information about anything that can be invoked Show what can be done with an object Shows what object stores are available
Get-command DEMO: DISCOVERY UTILITIES
Utilities Object Manipulation Command Compare Group Measure Select Sort Tee Where Action Compare 2 sets of objects Split a set of objects into groups Measure some property of a set of objects Select a set of properties from a set of objects Sort objects Make a copy of a set of objects Select a subset of objects
Set versus get DEMO: OBJECT MANIPULATION UTILITIES
Newsgroup: Microsoft.Public.Windows.PowerShell Team blog: http://blogs.msdn.com/powershell/ PowerShellCommunity.Org: http://www.powershellcommunity.org Channel 9 http://channel9.msdn.com/tags/powershell Wiki http://channel9.msdn.com/wiki/default.aspx/channel9.windowspowershellwiki Script Center: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx CodePlex: http://codeplex.com/project/projectdirectory.aspx?tagname=powershell Many excellent books Manning Press book by PowerShell Dev Lead Bruce Payette: PowerShell in Action http://manning.com/powershell/ O Reilly book by PowerShell Dev Lee Holmes Windows PowerShell Cookbook http://www.oreilly.com/catalog/9780596528492/index.html
Complete an evaluation
filesystem Vb http://www.microsoft.com/technet/scriptcenter/topics/wi npsh/payette2.mspx
tools powershellide (www.powershell.com) www.primalscript.com