Monday, February 15, 2021

USERPROFILE Environment Variable Resolves to C:\windows\system32\config\systemprofile via AWS Systems Manager

Context is important which is why different environment can and will produce different values. This time it happened when I ran a PowerShell script through AWS Systems Manager (SSM).

Problem

I intended to download a file reliably to Downloads directory through PowerShell script and AWS Systems Manager. 

At first, it seems straight forward, SSM Agent usually runs as ssm-user with administrator privilege. And USERPROFILE environment variable usually resolves to C:\Users\<username>, well, at least locally. So, $env:USERPROFILE\Downloads should work as intended. 

But it isn't so in my particular case. Instead, it resolves to C:\windows\system32\config\systemprofile\Downloads which of course doesn't exist and failed.

I also tried using $HOME and it resolves to the same path as $env:USERPROFILE.

Reading online, there are indicators that it happened on some machines and not the others. And also, this behavior has been around for a while.

Solution

Some solutions online suggest tweaking the registry but in my case, I'd rather not do that which might complicate the issue further.

And some solutions suggest using the Public user folder and another option is to use ProgramData folder. Both options are not very clear for my use case.

In the end, I decided to use and create a custom directory if it doesn't exist using the following script:

$DownloadDirectory="C:\temp"
if (!(Test-Path $DownloadDirectory)) {
    New-Item -ItemType directory -Path $DownloadDirectory
}

Of course, it will fail if somehow the SSM agent doesn't have permission to create a directory, but in my case, this is acceptable.

No comments:

Post a Comment