Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function Search-PSScripts{
- <#
- .SYNOPSIS
- Use to search the text inside PowerShell scripts for a particular string
- .PARAMETER SearchString
- The string to search for inside the script file
- .PARAMETER Path
- The folder path to search for PowerShell files in. Default to userprofile if not specified.
- .PARAMETER Recurse
- Indicates that this function gets the items in the specified locations and in all child items of the locations.
- .EXAMPLE
- Search-PSScripts -searchString "Get-Help" -recurse
- Description
- -----------
- This command searches all of the script files in the user's profile path and its subdirectories.
- .EXAMPLE
- Search-PSScripts -searchString "Invoke-WebRequest" -path 'C:\Scripts' -recurse
- Description
- -----------
- This command searches all of the script files in the current directory and its subdirectories.
- .EXAMPLE
- Search-PSScripts -searchString "Invoke-WebRequest" -path 'C:\Scripts'
- Description
- -----------
- This command searches only the script files in the current directory.
- #>
- [cmdletbinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SearchString,
- [Parameter(Mandatory=$false)]
- [string]$Path = $env:USERPROFILE,
- [Parameter(Mandatory=$false)]
- [switch]$Recurse
- )
- $filter = "*.ps1","*.psm1"
- # Confirm path is valid
- if(!(Test-Path $Path)){
- throw "'$Path' is not a valid folder or is not accessible."
- }
- # Get the name of this script to exclude it
- $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
- $progressParam = @{
- Activity = "Search for PowerShell Script in $Path"
- Status = "Depending on the number of scripts this may take some time"
- PercentComplete = 0
- id = 1
- }
- Write-Progress @progressParam
- # Get all files in the path
- if($Recurse){
- $fileList = Get-ChildItem $Path -Recurse -include $filter -Exclude $Invocation.MyCommand -File
- } else {
- $Path = (Join-Path $Path '*.*')
- $fileList = Get-ChildItem $Path -include $filter -Exclude $Invocation.MyCommand -File
- }
- [System.Collections.Generic.List[PSObject]] $results = @()
- $progress=1
- # Check each file for the string pattern
- Foreach($file in $fileList){
- $progressParam = @{
- Activity = "Search for '$SearchString' - $progress of $(@($fileList).count)"
- Status = "Found: $(@($results).count)"
- PercentComplete = $(($progress/$($fileList.count))*100)
- id = 1
- }
- Write-Progress @progressParam
- $progress++
- $found = Select-String -Path $file.fullname -pattern $SearchString
- if($found){
- Write-Verbose ($found | Out-String)
- $results.Add(($file | Select-Object LastWriteTime, FullName))
- }
- }
- Write-Progress -Activity "Done" -Id 1 -Completed
- # Return found scripts sorted by last write time
- $results | sort LastWriteTime
- }
Add Comment
Please, Sign In to add comment