使用IF语句Powershell检查多个目录中的文件 [英] Check for File in multiple directories with an IF statement Powershell
问题描述
名称是一个变量,如$ VM_DISK = VM_DISK.vhdx,并且让该PowerShell在该庄园中进行搜索,以便如果该文件存在于C:\VM_DISK\等文件夹中,则会退出该脚本。
我已经尝试过Get-Childitem,但是当我把变量放在它当中似乎不起作用。这是一个例子:
$ VM_DISK =Example.vhdx
$ search = Get- ChildItem -Path C:\VM_DISK\ * -Filter $ VM_DISK -Recurse
if($ search -eq $ VM_DISK){write-host再见! exit} else {write-hostContinue}
我似乎无法弄清楚为什么这是
你需要修改你的 code>语句。
if($ search.Name -contains $ VM_Disk)
这样你就可以将名称数组(这是你想要的,对象的名称,而不是对象)与特定对象的名称进行比较(基本上是一个字符串
)。
这在你的情况下没有什么意义,tbh。由于 $ search
将始终包含 $ VM_Disk
,或者如果没有找到内容将为null。
所以如果($ search)(就像Mathias建议),正确的测试方法是。这将测试是否有任何回报。哪个,基本上等于你想要做的。
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.
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.
这篇关于使用IF语句Powershell检查多个目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!