powershell if-else不跟随任何一个分支 [英] powershell if-else does not follow either branch

查看:278
本文介绍了powershell if-else不跟随任何一个分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有powershell代码

I have the powershell code

$target_dir = "\\server\share\"
$DelTmpStatus = "init value"
if ( Test-Path ( $target_dir + "receivals.tmp") )
{
    del ( $target_dir + "receivals.tmp")
    $DelTmpStatus = "Present and delete status $?"
} else {
    $DelTmpStatus = "NA"
}

有时它通过此部分使$ DelTmpStatus仍然设置为初始值。

and sometimes it makes it through this section with $DelTmpStatus still set to "init value".

if-else结构如何不遵循任何一条路径?当if函数被赋予错误而不是true或false时,powershell中的if-else结构是否没有做任何事情?

How can the if-else structure not follow either path? Does the if-else structure in powershell not do anything when the if function is given an error instead of true or false?

$ PSVersionTable.psversion是3.0

$PSVersionTable.psversion is 3.0

编辑:当我自己运行它时,我从来没有任何错误或这个问题,无论是完全还是一步一步。但有时候预定的作业会运行,$ DelTmpStatus仍然是初始值我想象当 \\\\\\\\\\\\\\\\\\\\\\\\\\服务器在低功耗模式下过夜需要很长时间才能响应并且测试路径功能超时。虽然我不能确定这是不是原因。

I never have any errors or this problem when I run it myself, either fully or step-by-step. But sometimes the scheduled job will run and $DelTmpStatus will still be "init value" I imagine it happens when the \\server\share\ path is unavailable due to server in low power mode overnight taking too long to respond and the test-path function times out. Though I can't be sure if that is the cause or not.

编辑:进行测试的结果


  • 使用不存在的服务器 $ target_dir 使其跟随else路径并设置 $ DelTmpStatus 到NA

  • 使用无效路径,例如 $ target_dir =C:\..\..\invalid\ 导致测试路径向stderr写入错误并返回true(不理想,但无论如何),使程序向下流动尝试删除文件(再次出现错误)然后设置 $ DelTmpStatus to显示和删除状态为False。这不是特别有用的事情,但至少执行了if-else语句中的代码。

  • using a non existent server for $target_dir makes it follow the else path and sets $DelTmpStatus to "NA"
  • using an invalid path like $target_dir = "C:\..\..\invalid\" results in test-path writing an error to stderr and returning true (not ideal but whatever), making the program flow down the attempt to delete the file (again there's an error) then it sets $DelTmpStatus to "Present and delete status False". This is not a particularly helpful thing to do but at least the code in the if-else statement is executed.

推荐答案

似乎如果条件区域内的命令无法执行并且没有返回值,则不执行整个if-else块,并且继续错误选择继续在if-else块下面。

It seems that if the command inside the condition area fails to execute and doesn't return a value, the entire if-else block is not executed and the continue on error chooses to continue below the if-else block.

如何模拟问题

虽然这不是什么继续我的实际代码,它确实产生了if-else块未被执行的相同问题。它甚至每次都这样做。

While this is not exactly what is going on in my real code, it does produce the same problem of the if-else block not being executed. It even does it every time.

if ( Test-Path -invalid-switch )
{
    write-output "true path of if statement"
} else {
    write-output "false path of if statement"
}
write-output "finished if statement"

有输出

Test-Path : A parameter cannot be found that matches parameter name 'invalid-switch'.
At C:\scripts\test.ps1:1 char:16
+ if ( Test-Path -invalid-switch )
+                ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Test-Path], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.TestPathCommand

finished if statement

修复

要解决此问题,可能需要从事先测试的if()条件中取出可能有错误的代码,并将逻辑添加到if语句以处理潜在的故障。要修复实际代码以免遭遇此问题,我现在已将代码更改为

To fix the issue the code that may have an error needs to be taken out of the if() condition tested beforehand, and logic added to the if-statement to deal with a potential failure. To fix up the actual code to not suffer from this problem I have now changed the code to

$err = $false
try { $tmpStatus = Test-Path ( $target_dir + "receivals.tmp") }
catch
{
    $tmpStatus = $error | foreach { $_.Exception }
    $err = $true
}
if ( $err -or $tmpStatus ) 
{
    del ( $target_dir + "receivals.tmp")
    $DelTmpStatus = $?
} else {
    $DelTmpStatus = "NA"
}

精明的人会意识到我只能用行代替所有这些

The astute will realise that I could just replace all of that with just the lines

$tmpStatus = test-path ( $target_dir + "receivals.tmp")
del ( $target_dir + "receivals.tmp")
$DelTmpStatus = $?

因为我尝试删除文件,即使它找到文件时出错也是如此。唯一的区别是较短的代码会更频繁地出错但仍然执行相同的功能。

since I try and delete the file even if it has an error finding the file. The only difference will be that the shorter code will have errors more often but still perform the same function.

然而,使用更长的代码和更多的错误检查可以减少更多的亮光关于$ tmpStatus已经通过值的情况

However having the longer code with more error checking sheds a bit more light on the situation as $tmpStatus has come through with the value

System.Management.Automation.CommandNotFoundException: The term 'Test-Path' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

不幸的是,这仍然让我想知道发生了什么......? 测试路径如何在某些日子里成为有效的cmdlet,而不是其他人,在同一台预定作业的同一台计算机上运行完全相同的脚本。作为额外的奖励,在'Test-Path'的日子里不是有效的cmdlet ,当我稍后在同一个脚本中再次使用它时,它每次都能正常工作。

Unfortunately this still leaves me wondering what is going on...? How can 'Test-Path' be a valid cmdlet some days but not others, with exactly the same script running on the same computer from the same scheduled job. As an extra bonus, on the days when 'Test-Path' is not a valid cmdlet, when I use it again later on in the same script it works fine every time.

这篇关于powershell if-else不跟随任何一个分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆