I'm having trouble understanding because we can't see the entire code. I ran you're code and it does work in my lab exactly as you stated.
If it's part of a larger script, it all depends on how your variables are defined, whether scoped properly.
If you are not willing to share the entire script, than, at least for myself, I cannot assist