#Prompt for a path and display some information about it $shell = New-Object -com "shell.application" $fldr=$shell.BrowseForFolder(0,"Select a Folder to Analyze",0,"c:\") $path=$fldr.self.path Write-Host "Examining $path" -ForegroundColor Green #filter out folders so that only files are measured $stats=dir -Path $path -Recurse | where {-not $_.PSIsContainer} | Measure-Object -Property Length -sum -max -average ##Create a custom object [PSCustomObject]@{Path=$path;FileCount=$stats.count;AverageSize=$stats.average;TotalSize=$stats.Sum;LargestFile=$stats.maximum} # Or before PowerShell V3.0 New-Object -TypeName PSObject -Property @{ Path=$path FileCount=$stats.count AverageSize=$stats.average TotalSize=$stats.Sum LargestFile=$stats.maximum } ##Get-ChildItem | Select-Object -First n -Last n -Skip n -Index n (offset, starts at 0) -Property name ## Two different cmdlets to read the event log # Get-EventLog can only be used for "standard" event logs - Application, Security, System, etc. Any filtering which is possible is left-filtered, so more efficient # Get the event id, time generated, and message from first 10 events in the application log Get-EventLog -logname application -Newest 10 | select eventid, timegenerated, message | fl * # Get the event id, time generated, and message from first 10 events in the application log on TestSrv Get-Eventlog -logname application -ComputerName TestSrv -Newest 10 | select eventid, timegenerated, message | fl * # Get the event id, time generated, and message from first 10 SQL Server events from the application log Get-Eventlog -logname application | where {$_.source -eq 'MSSQLSERVER'} | select -first 10 eventid, timegenerated, message | fl * # Get the event id, time generated, and message from first 10 events from the application log after 10/20/11 at 10am and before 10/21/2011 at 10am Get-Eventlog -logname application -newest 10 -after ([datetime]"10/20/2011 00:10:00") -before ([datetime]"10/21/2011 00:10:00") | select eventid, timegenerated, message # Look for events with messages containing a string (without wildcards, it looks for an exact match) Get-EventLog -logname Application -message "*vmguestlibrary*" ## http://blogs.technet.com/b/heyscriptingguy/archive/2014/06/03/use-filterhashtable-to-filter-event-log-with-powershell.aspx # Get-WinEvent -LogName application -MaxEvents n [-FilterHashTable @{params}] # GetWinEvent can be used for any event log. Standard logs can be specified with the -LogName parameter. All other logs must use the -FilterHashTable parameter # Get the event id, time generated, level, and message from first 10 events in the application log Get-WinEvent -FilterHashTable @{LogName="Application"} | select -first 10 id, timecreated, leveldisplayname, message # The valid key-value pairs are as follows: # -- LogName= # -- ProviderName= # -- Path= # -- Keywords= # -- ID= # -- Level= # -- StartTime= # -- EndTime= # -- UserID= # -- Data= # -- *= # Find events within a specified time range Get-WinEvent -FilterHashtable @{Logname='application';starttime='9/24/15';endtime='9/25/15'} # Find enents in the application log where the message contains the word "operation" Get-WinEvent -FilterHashtable @{Logname='application'} | where {$_.message -match "operation"} # Use event view to create a filter, then use that filter in a Get-WinEvent # Create the filter, click the XML tab, and select the portion of the XML which is after the name of the event log. For example, in the line: # # you would select "*[System[Provider[@Name='.NET Runtime']]]" # Create a variable and assign it that value $xpath = ">*[System[Provider[@Name='.NET Runtime']]]" # And then: Get-WinEvent -LogName Application -FilterXPath $xpath # OR (this seems a little clearer to me) # Create the filter, click on the XML tab, and select the entire XML text. # Then create a variable with the exact text enclosed in SINGLE quotes (it should be the entire "QueryList" keyword) $filterXML = 'paste the XML here' Get-WinEvent -FilterXml $filterXML # Get a list of all event logs Get-WinEvent -ListLog * # This command gets only event logs on the Server01 computer that contain events. Many logs might be empty. Get-WinEvent -ListLog * -ComputerName Server01 | Where-Object {$_.RecordCount} # This command gets all of the providers that write to the Application log on the local computer. (Get-WinEvent -ListLog Application).ProviderNames # Clear a non-standard event log Get-WinEvent -ListLog *winrm* | % {wevtutil.exe cl $_.LogName} # Enable the log, feeding it the "y" which is necessary Get-WinEvent -ListLog *winrm* | % {echo y | wevtutil.exe sl $_.LogName /e:true} # Verify that it is enabled Get-WinEvent -ListLog *winrm* | fl * # or (Get-WinEvent -ListLog *winrm*).isenabled # Disable the log Get-WinEvent -ListLog *winrm* | % {echo y | wevtutil.exe sl $_.LogName /e:false} # Find group policy events Get-WinEvent -FilterHashtable @{LogName="System";ProviderName="Microsoft-Windows-GroupPolicy"} -computername xxxxx # Get events from yesterday $yesterday = (Get-Date) - (New-TimeSpan -Day 1) Get-WinEvent -LogName "Windows PowerShell" | Where-Object {$_.TimeCreated -ge $yesterday} # Use a filterhashtable to get only level 3 events from yesterday $yesterday = (Get-Date) - (New-TimeSpan -Day 1) Get-WinEvent -FilterHashTable @{LogName='Windows PowerShell'; Level=3; StartTime=$yesterday} ##PS C:\> (get-host).privatedata # #ErrorForegroundColor : Red #ErrorBackgroundColor : Black #WarningForegroundColor : Yellow #WarningBackgroundColor : Black #DebugForegroundColor : Yellow #DebugBackgroundColor : Black #VerboseForegroundColor : Yellow #VerboseBackgroundColor : Black #ProgressForegroundColor : Yellow #ProgressBackgroundColor : DarkCyan function Get-Color { $colorDialog = New-Object System.Windows.Forms.ColorDialog $colorDialog.AllowFullOpen = $false [void]$colorDialog.ShowDialog() $colorDialog.Color.Name } ## Count the number of words, lines, characters in files Get-Content c:\work\r.txt | Measure-Object -Word -Line -Character | Format-List (dir *.txt | Get-Content | Measure-Object -word).words dir *.txt | foreach {$_.name; (Get-Content $_ | Measure-Object -word).words} ## Debugging information # test script: #requires -version 2.0 Write-Host "I am starting" -ForegroundColor Green $r = Read-Host "What is the radius maximum value?" $pi = [math]::pi $result = $pi*($r*$r) Write $result Write-Host "I am ending" -ForegroundColor Green # end of script # set a breakpoint at a line Set-PSBreakpoint -Script c:\scripts\fixme.ps1 -Line 6 # run the script PS C:\> c:\scripts\fixme.ps1 I am starting What is the radius maximum value?: 5 Hit Line breakpoint on 'C:\scripts\fixme.ps1:6' fixme.ps1:6 $result=$pi*($r*$r) [DBG]: PS C:\>>> [DBG]: PS C:\>>> $pi 3.14159265358979 [DBG]: PS C:\>>> $r 5 [DBG]: PS C:\>>> $r*$r 55555 [DBG]: PS C:\>>> $r.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object # remove the breakpoint Get-PSBreakpoint | Remove-PSBreakpoint # set a breakpoint when a variable changes Set-PSBreakpoint -Script c:\scripts\fixme.ps1 -Variable r PS C:\> c:\scripts\fixme.ps1 I am starting What is the radius maximum value?: 5 Hit Variable breakpoint on 'C:\scripts\fixme.ps1:$r' (Write access) fixme.ps1:4 $r = Read-Host "What is the radius maximum value?" [DBG]: PS C:\>>> list 1: #requires -version 2.0 2: 3: Write-Host "I am starting" -ForegroundColor Green 4:* $r = Read-Host "What is the radius maximum value?" 5: $pi = [math]::pi 6: $result=$pi*($r*$r) 7: Write $result 8: Write-Host "I am ending" -ForegroundColor Green 9: [DBG]: PS C:\>>> c 174531.179870181 I am ending PS C:\> c:\scripts\fixme.ps1 I am starting What is the radius maximum value?: 5 Hit Variable breakpoint on 'C:\scripts\fixme.ps1:$r' (Write access) fixme.ps1:4 [int]$r = Read-Host "What is the radius maximum value?" [DBG]: PS C:\>>> s fixme.ps1:5 $pi = [math]::pi [DBG]: PS C:\>>> s fixme.ps1:6 $result = $pi*($r*$r) [DBG]: PS C:\>>> $pi 3.14159265358979 [DBG]: PS C:\>>> $r 5 [DBG]: PS C:\>>> $r.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType [DBG]: PS C:\>>> c 78.5398163397448 I am ending # To allow -WhatIf and -Confirm processing, add the following line with a param() [CmdletBinding(SupportsShouldProcess=$true)] # The following line will make the script default to -Confirm [CmdletBinding(SupportsShouldProcess=$true),ConfirmImpact="High"] ## To use Write-Verbose and Write-Debug, you must enable cmdletbinding. That also requires the "param()" keyword (although you do not have to pass a parameter) [CmdletBinding()] Param() # Run this script with the -Verbose or -Debug parameter and you will get the appropriate output [CmdletBinding()] Param([string]$computername=$env:computername) Write-Verbose "Starting the script" Write-Debug "Computername = $computername" Write-Verbose "Testing connectivity to $computername" #verify computer can be pinged If (Test-Connection -computername $computername -quiet) { #my code here ... Write-Verbose "Ending script" ## Validation Function Get-Foo { Param ( [Parameter(Position=0,Mandatory=$True,HelpMessage="What computer do you want to process?")] # first parameter, and if you don't provide it, PS will prompt for it [ValidateNotNullOrEmpty()] # If you didn't enter the parameter, PS will throw error [ValidateScript({Test-Connection -ComputerName $_ -Quiet -Count 2})] # Script block must evaluate to "True" or "False" [ValidateScript({ Test-Path -Path "$env:windir\$_" })] [string]$computername, [Parameter(Position=1)] # second parameter [ValidateRange(1,50)] # must be from 1-50 [int]$Count, [Parameter()] [ValidateSet("User","Computer","Group")] # optional parameter -Item must be one of these values [string]$Item="User" # default is "User" [Parameter()[switch]$Switch ) Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a file path to process")] # Will display HelpMessage if you type !? when prompted for parameter value [string]$Path, [Parameter()] [switch]$Test ) ## Use output from command-line objects PS C:\> nbtstat /n Local Area Connection: Node IpAddress: [10.23.36.71] Scope Id: [] NetBIOS Local Name Table Name Type Status --------------------------------------- QUARK <20> UNIQUE Registered QUARK <00> UNIQUE Registered JDHITSOLUTIONS <00> GROUP Registered Wireless Network Connection: Node IpAddress: [0.0.0.0] Scope Id: [] PS C:\> $data = nbtstat /n | Select-String "<" PS C:\> $data QUARK <20> UNIQUE Registered QUARK <00> UNIQUE Registered JDHITSOLUTIONS <00> GROUP Registered # Must convert from type "MatchInfo" to "string" PS C:\> $lines = $data | foreach { $_.Line.Trim()} PS C:\> $lines QUARK <20> UNIQUE Registered QUARK <00> UNIQUE Registered JDHITSOLUTIONS <00> GROUP Registered # Split on one or more spaces, and create a hash table with the name, nbtcode, type, and status PS C:\> $lines | foreach {$temp = $_ -split "\s+" >> [PSCustomObject]@{Name=$temp[0];NbtCode=$temp[1];Type=$temp[2];Status=$temp[3]} } Name NbtCode Type Status ---- ------- ---- ------ QUARK <20> UNIQUE Registered QUARK <00> UNIQUE Registered JDHITSOLUTIONS <00> GROUP Registered ## Pipeline binding PS C:\> Get-Service wsearch | Stop-Service -passthru Status Name DisplayName ------ ---- ----------- Stopped wsearch Windows Search PS C:\> "wsearch","wuauserv" | Stop-Service -whatif What if: Performing operation "Stop-Service" on Target "Windows Search (wsearch)". What if: Performing operation "Stop-Service" on Target "Windows Update (wuauserv)". PS C:\> Get-Content C:\work\services.txt | Restart-Service -whatif What if: Performing operation "Restart-Service" on Target "Windows Search (wsearch)". What if: Performing operation "Restart-Service" on Target "Windows Update (wuauserv)". What if: Performing operation "Restart-Service" on Target "Windows Remote Management (WS-Management) (winrm)". What if: Performing operation "Restart-Service" on Target "Background Intelligent Transfer Service (bits)". PS C:\> Import-Csv c:\work\data.csv name comment data ---- ------- ---- bits ok service wuauserv ok update wsearch ok service PS C:\> Import-Csv c:\work\data.csv | Restart-Service -passthru Status Name DisplayName ------ ---- ----------- Running bits Background Intelligent Transfer Ser... Running wuauserv Windows Update Running wsearch Windows Search PS C:\> Import-Csv c:\work\data.csv svc comment data --- ------- ---- bits ok service wuauserv ok update wsearch ok service PS C:\> Import-Csv c:\work\data.csv | Select @{Name="Name";Expression={$_.svc}} | Restart-Service -whatif What if: Performing operation "Restart-Service" on Target "Background Intelligent Transfer Service (bits)". What if: Performing operation "Restart-Service" on Target "Windows Update (wuauserv)". What if: Performing operation "Restart-Service" on Target "Windows Search (wsearch)". PS C:\> Import-Csv c:\work\data.csv | Foreach { Restart-Service -name $_.svc -whatif}