[英]How can I check if specific files are within a folder and write to host if they are present or not
I'm trying to check if a list of files exists within a folder, if they do exist then write to host that they do if not write to host that they do not.我正在尝试检查文件夹中是否存在文件列表,如果它们确实存在,则写入主机,如果不写入主机,则它们不写入。
my code works to check if all the files exist however when trying to write to console it always evaluates to working even if files are missing.我的代码用于检查所有文件是否存在,但是在尝试写入控制台时,即使文件丢失,它也始终评估为正常工作。
this will return true for each file in $msis
if present in the folder如果
$msis
每个文件存在于文件夹中,这将返回 true
$Instance = "TEST"
$msipath = "D:\CCS\${Instance}\"
$msis = @("${msipath}CCS1.msi", "${msipath}CC2.msi", "${msipath}CCS3.msi", "${msipath}CCS4.msi")
foreach($msi in $msis){
$test = (Test-Path $msi) -PathType leaf)
write-host "$test"
}
I added and if else statement to check if $test
is true write-host "I Work"
else write-host "I Fail"
我添加了 if else 语句来检查
$test
是否为 true write-host "I Work"
else write-host "I Fail"
my issue is that even when the files are missing it will still evaluate to "I work" it's only when all files are not present that it evaluates to "I fail".我的问题是,即使文件丢失,它仍然会评估为“我工作”,只有当所有文件都不存在时,它才会评估为“我失败”。
What i'm trying to do is have it write to host "I fail" if one or more files are missing.我正在尝试做的是在丢失一个或多个文件时将其写入主机“我失败”。
if ($test -eq 'True')
{ write-host "I work" }
else
{
write-host "I fail"
}
If I understand your question:如果我理解你的问题:
$Instance = "TEST"
$msipath = "D:\CCS\${Instance}\"
$msis = @("${msipath}CCS1.msi", "${msipath}CC2.msi", "${msipath}CCS3.msi", "${msipath}CCS4.msi")
$test = $true
foreach($msi in $msis){
$test = $test -and (Test-Path $msi -PathType leaf)
if (-not $test) { break } # immediately exit the loop on the 1st False
}
write-host "$test"
Read Using break
in loops .阅读在循环中使用
break
。
After a little break and revisiting i have now managed to change up my script a little to get this to work.经过一段时间的休息和重新访问后,我现在设法稍微更改了我的脚本以使其正常工作。
$Instance = "TEST"
$msipath = "D:\CCS\${Instance}\"
$msis = @("${msipath}CCS1.msi", "${msipath}CCS2.msi", "${msipath}CCS3.msi", "${msipath}CCS4.msi")
if (($msis | foreach {test-path $msis}) -contains $false)
{
write-host "I Fail"
}
else
{
write-host "I Work"
}
This will now show "I fail" if any file within $msis
is missing.如果
$msis
任何文件丢失,现在将显示“我失败”。
Test-Path -Path
takes <string[]>
as input, meaning, it can evaluate multiple paths, there is no need to loop here: Test-Path -Path
以<string[]>
作为输入,意思是可以计算多个路径,这里不需要循环:
$Instance = "TEST"
$msipath = "D:\CCS\$Instance"
$msis = 'CCS1.msi', 'CCS2.msi', 'CCS3.msi', 'CCS4.msi' | ForEach-Object {
Join-Path $msipath -ChildPath $_
}
If((Test-Path $msis).Contains($false))
{
write-host "I Fail"
}
else
{
write-host "I Work"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.