Skip to content

Commit

Permalink
New version: 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
DarkCoderSc committed Feb 18, 2025
1 parent 48913a4 commit d17b7c5
Show file tree
Hide file tree
Showing 6 changed files with 308 additions and 356 deletions.
122 changes: 122 additions & 0 deletions PowerRunAs/PowerRunAs.psd1
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
#
# Module manifest for module 'PowerRunAs'
#
# Generated by: Jean-Pierre LESUEUR
#
# Generated on: 18/02/2025
#

@{

# Script module or binary module file associated with this manifest.
RootModule = 'PowerRunAs'

# Version number of this module.
ModuleVersion = '2.0.0'

# Supported PSEditions
# CompatiblePSEditions = @()

# ID used to uniquely identify this module
GUID = '5a822778-d1be-4b7b-8a29-ab45e3efb10c'

# Author of this module
Author = 'Jean-Pierre LESUEUR'

# Company or vendor of this module
CompanyName = 'Phrozen'

# Copyright statement for this module
Copyright = '(c) 2025 Phrozen. All rights reserved.'

# Description of the functionality provided by this module
Description = 'This module allows you to run a process (defaulting to PowerShell) as a different user by providing a known username and password. By default, the standard output (stdout), standard error (stderr), and standard input (stdin) are attached to the current console of the caller.'

# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''

# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''

# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''

# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''

# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()

# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()

# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()

# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @("Invoke-RunAs")

# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()

# Variables to export from this module
VariablesToExport = '*'

# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()

# DSC resources to export from this module
# DscResourcesToExport = @()

# List of all modules packaged with this module
# ModuleList = @()

# List of all files packaged with this module
# FileList = @()

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{

PSData = @{

# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()

# A URL to the license for this module.
# LicenseUri = ''

# A URL to the main website for this project.
# ProjectUri = ''

# A URL to an icon representing this module.
# IconUri = ''

# ReleaseNotes of this module
# ReleaseNotes = ''

} # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfo URI of this module
# HelpInfoURI = ''

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''

}
157 changes: 157 additions & 0 deletions PowerRunAs/PowerRunAs.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# ----------------------------------------------------------------------------------- #
# #
# .Developer #
# Jean-Pierre LESUEUR (@DarkCoderSc) #
# https://www.twitter.com/darkcodersc #
# https://github.com/PhrozenIO #
# https://github.com/DarkCoderSc #
# www.phrozen.io #
# [email protected] #
# PHROZEN #
# .License #
# Apache License #
# Version 2.0, January 2004 #
# http://www.apache.org/licenses/ #
# .Disclaimer #
# This script is provided "as is", without warranty of any kind, express or #
# implied, including but not limited to the warranties of merchantability, #
# fitness for a particular purpose and noninfringement. In no event shall the #
# authors or copyright holders be liable for any claim, damages or other #
# liability, whether in an action of contract, tort or otherwise, arising #
# from, out of or in connection with the software or the use or other dealings #
# in the software. #
# #
# ----------------------------------------------------------------------------------- #

$global:sharedData = @{
"StdErrTick" = 0
}

function Add-StdHandler
{
param (
[Parameter(Mandatory=$true)]
[System.IO.StreamReader] $Stream,

[bool] $StandardErrorFlag = $false
)

$runspace = [RunspaceFactory]::CreateRunspace()
$runspace.Open()

$runspace.SessionStateProxy.SetVariable("SharedData", $global:sharedData)
$runspace.SessionStateProxy.SetVariable("hostUI", $host.UI)
$runspace.SessionStateProxy.SetVariable("Stream", $Stream);
$runspace.SessionStateProxy.SetVariable("StandardErrorFlag", $StandardErrorFlag);

$powershell = [PowerShell]::Create().AddScript({
try
{
$sbData = New-Object System.Text.StringBuilder

while ($true)
{
$null = $sbData.Append([char]$Stream.BaseStream.ReadByte())

if ((-not $StandardErrorFlag) -and (([Environment]::TickCount - $SharedData.StdErrTick) -le 150))
{
Start-Sleep -Milliseconds 100

continue
}

if ($StandardErrorFlag)
{
$SharedData.StdErrTick = [Environment]::TickCount
}

$hostUI.Write($sbData.ToString())
$sbData.Clear()
}
}
catch {
break
}
})

$powershell.Runspace = $runspace

$null = $powershell.BeginInvoke()

return $runspace
}

function Invoke-RunAs
{
param (
[Parameter(Mandatory=$true)]
[string] $Username,

[Parameter(Mandatory=$true)]
[string] $Password,

[string] $Application = "powershell.exe",
[string] $Argument = "",
[string] $Domain = "",
[switch] $Detach
)

$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force

$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = $Application
$startInfo.WorkingDirectory = $env:SystemRoot
$startInfo.UseShellExecute = $false
$startInfo.Domain = $Domain
$startInfo.Username = $Username
$startInfo.Password = $securePassword
$startInfo.Arguments = $Argument

if (-not $Detach)
{
$startInfo.RedirectStandardError = $true
$startInfo.RedirectStandardOutput = $true
$startInfo.RedirectStandardInput = $true
$startInfo.CreateNoWindow = $true
}

$proc = New-Object System.Diagnostics.Process

$proc.StartInfo = $startInfo

$null = $proc.Start()

if (-not $Detach)
{
$runspaces = @()
try
{
$runspaces += Add-StdHandler -Stream $proc.StandardError -StandardErrorFlag $true
$runspaces += Add-StdHandler -Stream $proc.StandardOutput

while (-not $proc.HasExited)
{
$userInput = Read-Host

$proc.StandardInput.WriteLine($userInput)

if ($userInput.ToLower() -eq "exit")
{
break
}
}
}
finally
{
foreach ($runspace in $runspaces)
{
$runspace.Close()
$runspace.Dispose()
}
}
}
}

try {
Export-ModuleMember -Function Invoke-RunAs
} catch {}
Loading

0 comments on commit d17b7c5

Please sign in to comment.