PoshCode Archive  Artifact [c2d3710781]

Artifact c2d371078169a04f739194592edadfcd69f89193ac0d15b6546b1298ae348b19:

  • File runas-sudo.ps1 — part of check-in [7ea16fa99b] at 2018-06-10 13:42:39 on branch trunk — Actually, Start-Process cmdlet with -Verb RunAs can help you run process with admin’s rights, but… I do not like this cmdlet. I wanna something useable, so I wrote a prototype of something that looks like runas in cmd (or sudo in bash). (user: greg zakharov size: 1610)

# encoding: ascii
# api: powershell
# title: runas\sudo
# description: Actually, Start-Process cmdlet with -Verb RunAs can help you run process with admin’s rights, but… I do not like this cmdlet. I wanna something useable, so I wrote a prototype of something that looks like runas in cmd (or sudo in bash).
# version: 0.1
# type: function
# author: greg zakharov
# license: CC0
# function: Invoke-RunAs
# x-poshcode-id: 4534
# x-archived: 2015-05-06T17:43:45
# x-published: 2015-10-19T14:45:00
#
#
Set-Alias sudo Invoke-RunAs

function Invoke-RunAs {
  <#
    .LINK
        Follow me on twitter @gregzakharov
        http://msdn.microsoft.com/en-US/library/system.diagnostics.aspx
  #>
  param(
    [Parameter(Mandatory=$true)]
    [String]$Program,
    
    [Parameter(Mandatory=$false)]
    [String]$Arguments,
    
    [Parameter(Mandatory=$false)]
    [Switch]$LoadProfile = $false,
    
    [Security.SecureString]$UserName = (Read-Host "Admin name" -as),
    [Security.SecureString]$Password = (Read-Host "Enter pass" -as)
  )
  
  function str([Security.SecureString]$s) {
    return [Runtime.InteropServices.Marshal]::PtrToStringAuto(
      [Runtime.InteropServices.Marshal]::SecureStringToBSTR($s)
    )
  }
  
  $psi = New-Object Diagnostics.ProcessStartInfo
  $psi.Arguments = $Arguments
  $psi.Domain = [Environment]::UserDomainName
  $psi.FileName = $Program
  $psi.LoadUserProfile = $LoadProfile
  $psi.Password = $Password
  $psi.UserName = (str $UserName)
  $psi.UseShellExecute = $false
  
  [void][Diagnostics.Process]::Start($psi)
}