${Env:USERPROFILE} in administrator shell

This topic contains 5 replies, has 3 voices, and was last updated by Profile photo of Dan Potter Dan Potter 7 months, 3 weeks ago.

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #34837
    Profile photo of Andreas Öberg
    Andreas Öberg
    Participant

    Hello Powershell users.

    I have a script that will be running on local accounts on different machines, but the script itself needs admin privileges to run properly. The problem is that I need to use environment variables like ${USERPROFILE}, so the path will be correct on the current logged in user. No matter what computer I am using.

    Let's say A is a local account and B is a administrator, I am logged in as A, and need the homepath of A (c:\A ). ${USERPROFILE} usually gets me that, but I need to run this script with administrative privilages. So when I run the script in the administrative shell, still logged in as A, ${USERPROFILE} will be the path to Bs home profile (c:\B).

    I am not in any AD domain.

    Someone have any ideas of how I could get around this?
    I could post the full script if needed.

    Best regards Andreas

    #34838
    Profile photo of Ed O'Connor
    Ed O’Connor
    Participant

    Perhaps you could add a:

    Get-WMIObject -class Win32_ComputerSystem | select username

    command to get the logged on user and pipe that into your own variable representing the user variable.

    This command will get you the current logged on user even when in a elevated prompt.

    #34854
    Profile photo of Andreas Öberg
    Andreas Öberg
    Participant

    Hi Ed O'Connor! Thx for the reply!

    Get-WMIObject -class Win32_ComputerSystem | select username
    Does give me the username of current user, but I also get the Computername.. "Andreas-PC\Andreas"
    If I add that it will be "c:\UsersAndreas-PC\Andreas", which isnt the directory Iam looking for..

    Iam going to try to move around the problem..

    #34858
    Profile photo of Ed O'Connor
    Ed O’Connor
    Participant

    You can split the output of that command to get just the User Name like so:

    $CN_UN = Get-WmiObject -Class Win32_ComputerSystem | select username
    
    $SplitCN_UN = $CN_UN.username
    
    $UN = $SplitCN_UN.Split("\")
    
    $UN[1]
    
    

    Hopefully this gets you what you need.

    #34861
    Profile photo of Andreas Öberg
    Andreas Öberg
    Participant

    Thx again Ed O'Connor!

    Thats exactly what I need.
    Now I can solve the rest!

    Best Regards

    #34862
    Profile photo of Dan Potter
    Dan Potter
    Participant

    use credentials in your script?

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.