Using Remote $env user variable with invoke-command not working

Brass Contributor

In short, the script below is taking the $env:APPDATA info from my local computer instead of the $env:APPDATA info for the user currently logged on at remote computer, specified in the $computer variable. I have tried with no luck to search this in Google so I thought I would post here to see if anyone can help. Driving me crazy. Let me know if anything doesn't make sense.

Thanks in advance!

 

 

$computer = read-host 'Enter Computer Name'
invoke-command -computer $computer -scriptblock {Remove-Item -recurse "$env:APPDATA\Microsoft\Teams\blob_storage\*}

 

 

 

3 Replies

@charlie4872  Hello Charlie. You can try to get the variable from the remote machine with this. 

$computer = read-host 'Enter Computer Name'
invoke-command -computer $computer -scriptblock {Remove-Item -recurse "$([Environment]::GetEnvironmentVariable(“APPDATA”))\Microsoft\Teams\blob_storage\*"}

 

Regards

Erick Moreno 

@charlie4872

The variable APPDATA is a user enviroment variable and is present only in the user session...

APPDATA is builded runtime, in the user session!

So if you invoke locally (or remotely) your code or the following line

 

Get-CimInstance -ClassName win32_environment |Where{$_.name -match "appdata"}

 

you get nothing, and is the correct final result

The "no default" user variables are present in the registry in Computer\HKEY_CURRENT_USER\Environment  (appdata is not present)

 

varia.png

 

APPDATA is builded using %USERPROFILE% (session variable) and the string \AppData\Roaming

So you are approching the problem in the wrong way, that is the reason you getting crazy...

How to resolve the problem?

Get the remote users profile (or a single remote user) build the appdata and remove the teams blob storage

 

#returning "remote" builded appdata variables
(Get-CimInstance -ClassName win32_userprofile -ComputerName $computer |select localpath)| %{ "{0}\appdata\roaming" -f $_.localpath}

 

 

Bye Gas

 

@Erick A. Moreno R. 

Is a wrong concept and a wrong code as I explained  to @charlie4872 

Bye gas