Check for File in multiple directories with an IF statement Powershell

大兔子大兔子 提交于 2019-12-25 08:08:05

问题


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.



来源:https://stackoverflow.com/questions/40849639/check-for-file-in-multiple-directories-with-an-if-statement-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!