Check for File in multiple directories with an IF

2019-09-14 22:38发布

问题:

I am facing some problems in powershell. I want to be able to let a powershell command search for multiple directories. With the name being a variable like "$VM_DISK=VM_DISK.vhdx" and let powershell search in that manor so that if that file exists in a folder such as C:\VM_DISK\ it exit the script. I have already tried the "Get-Childitem" but it doesn't seem to work when I put my variable in it. Here is an example:

    $VM_DISK= "Example.vhdx"

    $search=Get-ChildItem -Path C:\VM_DISK\* -Filter $VM_DISK -Recurse 

    if ($search -eq $VM_DISK) {write-host "Goodbye!" exit}  else {write-host "Continue"}

I just cant seem to figure out why this isn't working, hope some can figure it out.

回答1:

You need to alter your if statement.

if ($search.Name -contains $VM_Disk)

This way you are comparing an Array of names (which is what you want, names of objects, not objects) to a name of particular object (to a string, basically).
This makes little sense in your case, tbh. Since $search would always include $VM_Disk or would be null if nothing was found.

So the proper way to test would be if ($search) (just like Mathias advised). Which would test if anything was returned. Which, basically equals what you are trying to do.