Home > Net >  PowerShell search file and display the result
PowerShell search file and display the result

Time:06-08

I want to search for a file in my C: and E: driver. If the file exists and then displays "File exists" Else: display File does not exist. I create the following code:

$filename = 'Myfile.exe'

Get-Childitem -Path C:\\, E:\\ -Include $filename -Recurse | %{$_.FullName}

$filename = 'Myfile.exe'
"Test to see if file $filename  exists"
if (Test-Path -Path $filename) {
    "file exists!"
} else {
    "File doesn't exist."
}

Note: Myfile may be in a different folder

When I run my scripts, I can see myfile.exe, but the result is "File doesn't exist."

What is wrong with my scripts?

CodePudding user response:

Technically speaking, your Get-ChildItem alone should suffice to let you know it's found the file by printing it's full path. Anyways, as MisterSmith mentions in his comment, you would need to place your conditional statements inside your Foreach-Object to get your expected result.

Here's my take on this:

$filename = 'Myfile.exe'
if (Get-Childitem -Path "C:\", "E:\" -Include $filename -Recurse -OutVariable "Found") {
    Write-Output -InputObject "File exists!"
    #$found.FullName
}
else {
    Write-Output -InputObject "File doesn't exist."
}

Leveraging PowerShell's flexibility of allowing the entirety of the expression to be placed inside your if() statement, that's all you would need here. Once the file is found, have it output that the file exists, else, say it doesn't.

  • The -OutVariable parameter allows you to save the object to a variable ($found) in case you need to reference any of it's properties later on.
  • Related