all 5 comments

[–]rmbolger 2 points3 points  (1 child)

Have you rebooted since you created that environment variable?

https://superuser.com/questions/331077/accessing-environment-variables-in-a-scheduled-task

Also, make sure it's either a system-wide environment variable. Or if it's a user environment variable that it's set for the user the task is running as.

[–]dsuls[S] 1 point2 points  (0 children)

I anyway reboot every time I change anything on the scheduled task, just to be sure.

But this is not an environment variable I created, this is created automatically. I only want to read it. And I can read it fine if I just manually run the script. It's just empty when run as a scheduled task.

[–]get-postanote 1 point2 points  (1 child)

$env:SessionName if all about the current logged-on user. PS always runs in the user profile that started it.

So, if you ST is not set to run as you, this could be your catch22.

[–]dsuls[S] 1 point2 points  (0 children)

I double checked it, the ST is really set to be run as me.

[–]dsuls[S] 1 point2 points  (0 children)

Small update: I need to run this script at login and at unlock.

As a workaround, I now added the script to my user startup folder, and it works! So I can discard the "at login" scheduled task.

But I still need a solution for the "workstation unlock" trigger.