Archive | Powershell tips RSS for this section

Find text (string) in text file(s)

If you want to find a certain text (string) in a text file or multiple text files, the quickest way to do so, is by using the select-string option.

First you’d need to get a list of the files you want to search trough:

$FileList = Get-ChildItem -Path "D:\temp\"
or you can use it on a single file as well
$FileList = Get-ChildItem -Path "D:\temp\file.txt"

After that, you can use select-string to find all files which contains the string you like to search for (in this case I’m searching for the text ‘success’):
$Success = $FileList | Select-String -Pattern 'success'

The variable $Success now has the following properties:
Context
Filename
IgnoreCase
Line
LineNumber
Matches
Path
Pattern

Out of which these are usually the most interesting ones in this kind of search:
Line (the text in the line select-string found the text you’re searching for)
Path (path & file name to the file)

Searching through a directory with about 50 files, which have a total size of 12,6MB and over 200.000 matches, only took 2 seconds this way. As far as I know, this is the quickest way to search through files with PowerShell.

Instead of a simple text search, you can also direct the select-string cmdlet to detect multiple matches per line, display text before and after the match, or display only a Boolean value (True or False) that indicates whether a match is found. Select-String uses regular expression matching, but it can also perform a simple match that searches the input for the text that you specify; like in my example above.

Have fun using this great and quick cmdlet. If you know of any quicker and easier ways to find text or patterns in files, let me know in the comments below and maybe my next blog post will be about that.

Remember that those who forget to script, are doomed to repeat their work!

Exporting all scheduled tasks

I wanted to have an export of all scheduled tasks ready for all servers that I manage, thus I created a little powershell tool that does that exactly.

It appeared to be pretty simple to reach this goal, as there is an Export-ScheduledTask function in Powershell.

This is what I used, but I wanted to have an export of all my scheduled tasks, without the default ones from Microsoft. So I needed to filter out a little bit.
There are two lines of code to filter out the unwanted tasks. First I removed the ones in the sub folder Microsoft and OfficeSoftwareProtection. After I run trough them to save the export (xml) of the task, I check if the task name doesn’t contain the text “User_Feed_Synchronization” or “Optimize Start Menu Cache Files”, if they aren’t called that, they’ll be exported.

(Get-ScheduledTask).TaskPath | Where { ($_ -notmatch "Microsoft") -and ($_ -notmatch "OfficeSoftware") } | Select -Unique
If(($TaskName -match "User_Feed_Synchronization") -or ($TaskName -match "Optimize Start Menu Cache Files"))

Troughout the running of the tool, it’ll output information to its log file. The files are saved in subdirectory names which correspond to the scheduled task folder they are found in.

This is the complete code for the tool:
$LogFile = "D:\Data\Logging\ExportScheduledTasks.log"
$BackupPath = "D:\Data\Tasks"
$TaskFolders = (Get-ScheduledTask).TaskPath | Where { ($_ -notmatch "Microsoft") -and ($_ -notmatch "OfficeSoftware") } | Select -Unique
Start-Transcript -Path $LogFile
Write-Output "Start exporting of scheduled tasks."

If(Test-Path -Path $BackupPath)
{
Remove-Item -Path $BackupPath -Recurse -Force
}
md $BackupPath | Out-Null

Foreach ($TaskFolder in $TaskFolders)
{
Write-Output "Task folder: $TaskFolder"
If($TaskFolder -ne "\") { md $BackupPath$TaskFolder | Out-Null }
$Tasks = Get-ScheduledTask -TaskPath $TaskFolder -ErrorAction SilentlyContinue
Foreach ($Task in $Tasks)
{
$TaskName = $Task.TaskName
If(($TaskName -match "User_Feed_Synchronization") -or ($TaskName -match "Optimize Start Menu Cache Files"))
{
}
Else
{
$TaskInfo = Export-ScheduledTask -TaskName $TaskName -TaskPath $TaskFolder
$TaskInfo | Out-File "$BackupPath$TaskFolder$TaskName.xml"
Write-Output "Saved file $BackupPath$TaskFolder$TaskName.xml"
}
}
}

Write-Output "Exporting of scheduled tasks finished."
Stop-Transcript

How simple some things can be – Powershell indent

In the past few years, I’ve been using tools to indent my code… Today by accident found out that in Powershell ISE, if you select multiple lines and press tab it’ll indent all selected lines… and of course shift+tab will do the reverse.

Amazing how simple some things can be without any tool… And how I’ve never before thought about trying this and automatically went looking to create my own or find an external solution once I couldn’t find it in any menu.

Quick command to open explorer from the current directory in Powershell

Here is a quick command if you want to open Windows Explorer from the current directory in Powershell:

ii .

(note the space between the ‘i’ and the dot)
ii is powershell’s alias for invoke-item. Adding a dot to that command will open the current directory using the default explorer.

Edit: If you’d like to achieve the same at a command prompt, you can run

explorer .