Search code examples
stringpowershelllocationsubstringexchange-server

Powershell: How to get the location of a file, depending on its name?


So my task is to write a PS script, that outputs the location of a database file. The location of the file is:

C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\Mailbox database Name\Mailbox database Name.edb 

I figured I can get the name of my Exchange database with

Get-MailboxDatabase | fl Name

which has the output:

Mailbox Database 0161713049

which is the name of the db but there is a bunch of invisible characters before and after the actual name.

So my question is, how could I get rid of these invisible characters? I want to concat a string to make it look like this:

C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\Mailbox Database 0161713049\Mailbox Database 0161713049.edb

I would need this code to work on servers with completely different database names too, so simply removing the unwanted characters from the start with .Remove() may help, but since I don't know for sure the length of the name of the database, I can't remove the characters at the end.

Also I can't get rid of the feeling that there is a much simpler way to get the location of my .edb file.


Solution

  • Powershell treats almost all outputs as an object with properties in hashtable format like @{Name=MYEXCHDB}. When you just want a property value as a string instead, you must expand it like @AdminOfThings suggests:

    Get-MailboxDatabase | Select-Object -ExpandProperty Name
    

    To concatenate the name into a string:

    $myString = "C:\path\to\$(Get-MailboxDatabase | Select-Object -ExpandProperty Name)"
    

    And as @mathias-r-jessen suggests, the path to the database is another property you can get directly:

    Get-MailboxDatabase | Select-Object -ExpandProperty EdbFilePath | Select-Object -ExpandProperty PathName