Question

The script below demonstrates the unexpected behavior in powershell which baffles me. The issue is most likely something I'm doing wrong, but I'm unable to figure it out. The script looks at specific times of specific days and depending on a set of parameters it takes various actions. I have a Boolean which alternates on iterations of the included loop. Or at least it should, therein lies the problem. Here's an example script which demonstrates how I'm using the variables and produces the odd behavior:

$DisabledRequests = $false
$Time = Get-Date -UFormat %R
$Day = Get-Date -UFormat %u

function checktime() {


if($Time -ge "07:00" -and $Time -le "19:00" -and $Day -le "5"){

    if($DisabledRequests -eq $false){
        Write-Host "Time is $time, Day is $day.  Inside disabledrequests -eq false statement."
        $DisabledRequests = $true #Sets variable to true
        $DisabledRequests -eq $true #Prints true on the console because the statement is true
    }else{


    }

}else{

    Write-Host "Outside limited time parameters."
    if($DisabledRequests -eq $true){
            Write-Host "Changing disabled requests var to false."
            $DisabledRequests = $false
    }
}

}


for($i=0; $i -le 10; $i++){
checktime
}

The expected behavior is that the script should loop though the conditional (at the present moment the conditional relative to time should result in $true) and then another conditional checking the status of the $DisabledRequests variable. Because the variable is initially $false the conditional runs correctly on the first iteration. Part of that conditional's actions is to set the variable $DisabledRequests to $true, which it does. At least, the part about $DisabledRequests -eq $true prints "True" on the console.

The problem is, if the $DisabledRequests variable is now true, why is the conditional ($DisabledRequests -eq $false) still being evaluated as true?

EDIT:

I'd like to also add that I've attempted to clear the variable with Clear-Variable and then recreate it with Set-Variable as true, and that doesn't work as expected either.

Était-ce utile?

La solution

Your problem is related to scoping - variables created (assigned w/ an explicit scope qualifier) inside a function cease to exist after the function exits.

If, when you assign to the variable, you use:

$script:DisabledRequest = $true

Then you'll see what you expect. For more information about scopes, you can read the topics from built-in help 'about_Scopes' and 'about_Variables', available online here: http://technet.microsoft.com/en-us/library/hh847849.aspx and http://technet.microsoft.com/en-us/library/hh847734.aspx.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top