PoshCode Logo PowerShell Code Repository

Start-ProcessAsUser.ps1 by Lee Holmes 17 months ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2225"></script>download | new post

From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes

  1. ##############################################################################
  2. ##
  3. ## Start-ProcessAsUser
  4. ##
  5. ## From Windows PowerShell Cookbook (O'Reilly)
  6. ## by Lee Holmes (http://www.leeholmes.com/guide)
  7. ##
  8. ##############################################################################
  9.  
  10. <#
  11.  
  12. .SYNOPSIS
  13.  
  14. Launch a process under alternate credentials, providing functionality
  15. similar to runas.exe.
  16.  
  17. .EXAMPLE
  18.  
  19. PS >$file = Join-Path ([Environment]::GetFolderPath("System")) certmgr.msc
  20. PS >Start-ProcessAsUser Administrator mmc $file
  21.  
  22. #>
  23.  
  24. param(
  25.     ## The credential to launch the process under
  26.     $Credential = (Get-Credential),
  27.  
  28.     ## The process to start
  29.     [Parameter(Mandatory = $true)]
  30.     [string] $Process,
  31.  
  32.     ## Any arguments to pass to the process
  33.     [string] $ArgumentList = ""
  34. )
  35.  
  36. Set-StrictMode -Version Latest
  37.  
  38. ## Create a real credential if they supplied a username
  39. $credential = Get-Credential $credential
  40.  
  41. ## Exit if they canceled out of the credential dialog
  42. if(-not ($credential -is "System.Management.Automation.PsCredential"))
  43. {
  44.     return
  45. }
  46.  
  47. ## Prepare the startup information (including username and password)
  48. $startInfo = New-Object Diagnostics.ProcessStartInfo
  49. $startInfo.Filename = $process
  50. $startInfo.Arguments = $argumentList
  51.  
  52. ## If we're launching as ourselves, set the "runas" verb
  53. if(($credential.Username -eq "$ENV:Username") -or
  54.     ($credential.Username -eq "\$ENV:Username"))
  55. {
  56.     $startInfo.Verb = "runas"
  57. }
  58. else
  59. {
  60.     $startInfo.UserName = $credential.Username
  61.     $startInfo.Password = $credential.Password
  62.     $startInfo.UseShellExecute = $false
  63. }
  64.  
  65. ## Start the process
  66. [Diagnostics.Process]::Start($startInfo)

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me