Set drive letter variable from a block of text

sample of the text contained in $message variable

BackupIoRequest::ReportIoError: write failure on backup device ‘G:\Backup\Full_Backups\foldername\databasename_backup_2015_01_15_001035_2007852.bak’. Operating system error 112(There is not enough space on the disk.).

$message = Get-EventLog -LogName Application | Where-Object {$_.EventID -eq 18210} | Select-Object -First 1 -ExpandProperty message
$driveletter = # I need a way to capture the drive letter from $message

Message is rarely the best way to pull information out of event logs (though it’s possible). Instead, look at the contents of the ReplacementStrings property. It’s an array of strings, and one of them is likely to contain the path you’re after. Once you’ve identified the right index for event ID 18210, you can hard-code that index in your script; it’ll always be the same.

According to , it looks like that index will be 2, so try something like this:

$event = Get-EventLog -LogName Application | Where-Object {$_.EventID -eq 18210} | Select-Object -First 1
$path = $event.ReplacementStrings[2]

if ($path -match '^([a-z]):')
    $driveLetter = $matches[1]
    Write-Error "Path '$path' does not contain a drive letter."

Thanks Dave!

I had forgotten about the ReplacementStrings Property. Very powerful stuff. As a follow up question in your script where does the $matches variable get set?

When I ran your script on the test server $matches was empty or null. Thanks again in advance!


How about this?

$18210 = Get-EventLog -LogName Application -EntryType Error -Source SQL | Where-Object {$_.EventID -eq 18210} | Select-Object -First 1
$path = $18210.ReplacementStrings[2]
$driveletter = $path[0]+$path[1]

$matches is an automatic variable that gets set when you use the -match operator (and the match is successful.) I’m not sure why you’d be seeing it as null or empty if you ran my code as-is. For example:

$string = 'C:\Something\Whatever.ext'
if ($string -match '^([a-z]):')
    Write-Host "Drive Letter: $($matches[1])"