Search code examples
windowspowershellpowershell-core

How to Register-PSRepository for another user?


In this environment, users (theuser account) are not permitted to install PowerShell. An IT person runs on the users machine with an elevated administrative account (admuser account) and installs PowerShell Core.

How can the admuser use Register-PSRepository to create a PSRepository for the theuser account?

Additional information:

The IT (admin) user installs PowerShell Core and runs a script I created to Set-ExecutionPolicy, Enable-PSRemoting, Install-Module (several), and other actions to prepare the system for end user use. It should Register-PSRepository for one or more NuGet repos in order to install modules from our internal NuGet repos. However, Register-PSRepository only registers the repository for the currently logged in user which is the admin user. In addition, the modules should be installed with -Scope CurrentUser since the user account should be able to Update-Module without requiring an admin account.

How can the script be changed to cause Register-PSRepository for the user and not the currently logged in admin user? Is this a call for impersonation?


Solution

  • To automate your task, have the admin user, from an elevated session, load the target user's registry hive using reg.exe load HKU\<username> C:\Users\<username>\ntuser.dat and then specify a run-once command that runs the PowerShell CLI with the Register-PSRepository call via that hive's Software\Microsoft\Windows\CurrentVersion\RunOnce key, which will run the next time the target user logs on.

    • Put the following into a script (.ps1) file...
    • ... and adapt it:
      • Specify the target username as the value of $targetUser (you could easily parameterize the script).
      • Replace the sample PowerShell command stored in $commandLine with your Register-PSRepository call.
    #requires -RunAsAdministrator
    
    # Set the target user's username.
    $targetUser = 'jdoe'
    
    # Load the target user's registry hive.
    # NOTE: Make sure that the user isn't currently logged on, 
    #       otherwise this will fail.
    $null = reg.exe load HKU\$targetUser C:\Users\$targetUser\ntuser.dat
    if ($LASTEXITCODE) { exit $LASTEXITCODE }
    
    # Formulate the command line to run when the target 
    # user logs in next (only once).
    # Note: For simplicity, a simple Write-Output call is used here.
    #       Substitute your Register-PSRepository call here.      
    $cmdLine = '"{0}" -Command Write-Output \"Hello, world.\"; pause' -f (Get-Process -Id $PID).Path
    
    # Create a registry value that makes the command line run 
    # (visibly) when the target user logs in next time.
    # Note: "PSRepoRegistration" is a self-chosen name.
    $runOnceKey = "registry::HKEY_USERS\$targetUser\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    Set-ItemProperty -ErrorAction Stop $runOnceKey PSRepoRegistration $cmdLine