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

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.

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

Related

Looking to validate that certain string is present in a text file, send warning if not

I have a process where files containing data are generated in separate locations, saved to a networked location, and merged into a single file.
And the end of the process, I would like to check that all locations are present in that merged file, and notify me if not.
I am having a problem finding a way to identify that a string specific to each location isn't present, to be used in an if statement, but it doesn't seem to be identifying the string correctly?
I have tried :
get-childitem -filter *daily.csv.ready \\x.x.x.x\data\* -recurse | where-object {$_ -notin 'D,KPI,KPI,1,'}
I know it's probably easier to do nothing if it is present, and perform the warning action if not, but I'm curious if this can be done in the reverse.
Thank you,
As Doug Maurer points out, your command does not search through the content of the files output by the Get-ChildItem command, because what that cmdlet emits are System.IO.FileInfo (or, potentially, System.IO.DirectoryInfo) instances containing metadata about the matching files (directories) rather than their content.
In other words: the automatic $_ variable in your Where-Object command refers to an object describing a file rather than its content.
However, you can pipe System.IO.FileInfo instances to the Select-String cmdlet, which indeed searches the input files' content:
Get-ChildItem -Filter *daily.csv.ready \\x.x.x.x\data\* -Recurse |
Where-Object { $_ | Select-String -Quiet -NotMatch 'D,KPI,KPI,1,' }

How can I convert installdate to a different format?

I am trying to run this command on cmd:
wmic:root\cli>/node:IPAddress product get name, version, vendor, installdate
IPAddress can be replaced with whatever address or hostname is desired.
The command does not give me any errors, however, it gives me installdate in MMMMYYDD form (for example, 20170801 instead of something simple like 01-Aug-2017 or 2017/08/01). I have tried to look for solutions online, but they're usually talking about system installations instead of product installations.
I know that installdate is a string, so this is more a question of how should I convert this string into a date. I tried using '+%Y%m%d' after the installdate, but it gave me an error: Invalid GET Expression.
If you can use PowerShell, it is not too difficult. You can control the format you want in the ToString method.
Get-CimInstance -ClassName CIM_Product |
Select-Object -Property #{n='Name';e={$_.Name}}, #{n='Date';e={([datetime]::ParseExact($_.InstallDate,'yyyyMMdd', $null)).ToString('dd-MMM-yyyy')}}

Find and replace a specific string within a specific file type located in wildcard path

Problem:
Update a specific string within numerous configuration files that are found within the subfolders of a partial path using PowerShell.
Expanded Details:
I have multiple configuration files that need a specific string to be updated; however, I do not know the name of these files and must begin my search from a partial path. I must scan each file for the specific string. Then I must replace the old string with the new string, but I must make sure it saves the file with its original name and in the same location it was found. I must also be able to display the results of the script (number of files affected and their names/path). Lastly, this must all be done in PowerShell.
So far I have come up with the following on my own:
$old = "string1"
$new = "string2"
$configs = Get-ChildItem -Path C:\*\foldername\*.config -Recurse
$configs | %{(Get-Content $_) -Replace $old, $new | Set-Content $_FullName
When I run this, something seems to happen.
If the files are open, they will tell me that they were modified by another program.
However, nothing seems to have changed.
I have attempted various modifications of the below code as well. To my dismay, it only seems to be opening and saving each file rather than actually making the change I want to happen.
$configFiles = GCI -Path C:\*\Somefolder\*.config -Recurse
foreach ($config in $configFiles) {
(GC $config.PSPath) | ForEach-Object {
$_ -Replace "oldString", "newString"
} | Set-Content $config.PSPath)
}
To further exasperate the issue, all of my attempts to perform a simple search against the specified string seems to be posing me issues as well.
Discussing with several others, and based on what have learned via SO... the following code SHOULD return results:
GCI -Path C:\*\Somefolder\*.config -Recurse |
Select-String -Pattern "string" |
Select Name
However, nothing seems to happen. I do not know if I am missing something or if the code itself is wrong...
Some questions I have researched and tried that are similar can be found at the below links:
UPDATE:
It is possible that I am being thwarted by special characters such as
+ and /. For example, my string might be: "s+r/ng"
I have applied the escape character that PowerShell says to use, but it seems this is not helping either.
Replacing a text at specified line number of a file using powershell
Find and replacing strings in multiple files
PowerShell Script to Find and Replace for all Files with a Specific Extension
Powershell to replace text in multiple files stored in many folders
I will continue my research and continue making modifications. I'll be sure to notate anything that get's me to my goal or even a step closer. Thank you all in advance.

Trying to Export a CSV list of users using Active Directory Module for Windows Powershell

So the below is where I'm at so far:
import-module activedirectory
$domain = "ourdomain"
Get-ADUser -Filter {enabled -eq $true} -Properties whenCreated,EmailAddress,CanonicalName |
select-object Name,EmailAddress,CanonicalName,whenCreated | export-csv C:\Data\test.csv
Unfortunately, when I run the above I get dates in two different formats in the CSV, e.g.:
01/01/2017
1/01/2017 8:35:56 PM
The issue this poses is that there isn't really a clean way to sort them. Excel's formatting doesn't change either of these formats to be more like the other, both because of the inclusion of time in one and not the other, and because the time-inclusive format doesn't use trailing zeroes in the single digit numbers, but the time-exclusive format does.
We have an existing script that captures users using the LastLogonTimestamp attribute that does this correctly by changing the bottom line to the following:
select-object Name,EmailAddress,CanonicalName,#{Name="Timestamp"; Expression={[DateTime]::FromFileTime($_.whenCreated).ToString('yyyy-MM-dd_hh:mm:ss')}}
For some reason this expression runs properly when we query the LastLogonTimestamp attribute, but when we run this version querying the whenCreated attribute, we get an entirely blank column underneath the Timestamp header.
I'm not particularly knowledgeable about PowerShell itself, and my colleague who had found the original script for the LastLogonTimestamp just found it online and adapted it as minimally as possible to have it work for us, so I don't know if something in this line would work properly with one of these attributes and not the other. It seems strange to me though that two attributes using dates in the same program would store them in different formats though, so I'm not convinced that's it.
In any case, any help anyone can offer to help us get a uniform date format in the output of this script would be greatly appreciated - it needn't have the time included if it's easier to do away with it, though if they're equally easy we may as well keep it.
whencreated is already a [DateTime]. Notice the difference between the properties when you run something like this:
Get-ADUser TestUser -Properties lastlogon,whenCreated | select lastlogon,whenCreated | fl
(Get-ADUser TestUser -Properties lastlogon).lastlogon | gm
(Get-ADUser TestUser -Properties whenCreated).whenCreated | gm
This means that you don't have to convert to a DateTime before running the toString() method.
select-object #{Name="Timestamp"; Expression={$_.whenCreated.ToString('yyyy-MM-dd_hh:mm:ss')}}

powershell Get-ChildItem iis:\sites | Export_CliXml sites.xml doesn't result in same as string output

Short:
Get-ChildItem IIS:\Sites
Get-ChildItem IIS:\Sites | Get-CliXml sites.xml
returns one thing as string and another as xml. Why?
Longer:
When I run
Get-ChildItem IIS:\Sites
I get something in the line of
Name ID State Phys...
Default Web Site 1 Started C:\i...
MyTestSite 2 Started C:\i...
but when I pipe it to Export-CliXml like so:
Get-ChildItem IIS:\Sites | Get-CliXml sites.xml
I get nothing with "Default Web Site" or "MyTestSite" in it. => The string and xml don't have anything in common.
When I do the same with Get-Process
Get-Process | Export-CliXml processes.xml
I can find my processes in the output file. => What is in the string can be found in the xml.
Why does Get-Process output about the same as text and xml
while Get-ChildItems IIS:\Sites one text and something else as xml?
What is it I have misunderstood?
I guess a problem might be that I get an exception from Get-ChildItem iis:\sites but output is still generated. The xml output seems ok too.
Update:
When I do
Get-ChildItem IIS:\Sites | select Name,ID,State,PhysicalPath | Get-CliXml sites.xml
I get the values I am looking for.
When I add Bindings
Get-ChildItem IIS:\Sites | select Name,ID,State,PhysicalPath,Bindings | Get-CliXml sites.xml
only 2 sites are iterated and I get an error message. The xml is fine anyway. (some well constructed try-catch in the code i believe)
Can someone confirm or deny that
get-childitem iis:\sites
gives back an object with lots of objects (not strings and integers)
and when this is piped to
export-clixml
the code will do a ToString on every property and return type names for them.
If the above is the case (which it probably is) the solution is to
Get-ChildItem IIS:\Sites | select Name,ID,State,PhysicalPath | Get-CliXml sites.xml
but not for complex properties like Binding.

Resources