Lerch Web Wiki

Random, erratic, no responsibility is taken for the correctness of this information

User Tools

Site Tools


powershell:basics:functions

Usefull functions for different tasks

Sample-Profile.ps1
$Global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$admingroup = [System.Security.Principal.WindowsBuiltInRole]::Administrator 
$Global:admin = ""
$principal = New-Object System.Security.Principal.WindowsPrincipal($CurrentUser)
$UI = $host.UI
$rawUI = $host.UI.RawUI
if ($principal.IsInRole($admingroup)){
    $admin = "*ADMIN*"
    $rawUI.WindowTitle = "!!! ATTENTION - This is an ADMIN Shell !!!"
}
 
$Global:bits = [IntPtr]::Size * 8
 
function prompt
{
	"$($admin)$($bits)bit_PS $(get-location)> "
}
Log2File.ps1
function Log2File{
    param(
	[string]$log,
	[string]$text
    )
    "$(Get-Date -Format "yyyyMMdd-HH:mm:ss"):`t$text" | Out-File -FilePath $log -Append
    Write-Verbose "$(Get-Date -Format "yyyyMMdd-HH:mm:ss"):`t$text" 
}
Get-ConsoleText.ps1
function Get-ConsoleText
{
	# Check the host name and exit if the host is not the Windows PowerShell console host. 
	if ($host.Name -ne 'ConsoleHost') 
	{ 
		Write-Host "This script runs only in the console host. You cannot run this script in $($host.Name)." -ForegroundColor DarkRed 
		exit -1
	} 
 
	$textBuilderConsole = New-Object System.Text.StringBuilder
	$textBuilderLine = New-Object System.Text.StringBuilder
 
	# Grab the console screen buffer contents using the Host console API.
	$bufferWidth = $host.UI.RawUI.BufferSize.Width - 1 
	$bufferHeight = $host.UI.RawUI.CursorPosition.Y 
	$rec = New-Object System.Management.Automation.Host.Rectangle(0,0,($bufferWidth),$bufferHeight)
	$buffer = $host.UI.RawUI.GetBufferContents($rec) 
 
	# Iterate through the lines in the console buffer. 
	for($i = 0; $i -lt $bufferHeight; $i++) 
	{ 
		for($j = 0; $j -lt $bufferWidth; $j++) 
		{ 
			$cell = $buffer[$i,$j] 
			$null = $textBuilderLine.Append($cell.Character)
		}
		$null = $textBuilderConsole.AppendLine($textBuilderLine.ToString().TrimEnd())
		$textBuilderLine = New-Object System.Text.StringBuilder
	}
 
	$textBuilderConsole.ToString() | clip
	Write-Host "$bufferHeight lines have been copied to the clipboard" -ForegroundColor DarkGreen
}
Get-SystemFolders.ps1
function Get-SystemFolders
{
	foreach ($f in [Enum]::GetValues([System.Environment+SpecialFolder]))
	{
		"{0,-20} - {1}" -f $f, [Environment]::GetFolderPath($f)
	}
}
Copy-CommandLine.ps1
function Copy-CommandLine
{
    param([int]$CommandHistoryNumber = 0)
	if ($CommandHistoryNumber -eq 0)
	{
		Write-Host "The command history index has not been specified" -ForegroundColor DarkYellow
		Write-Host "Assuming the last command shall be copied into clipboard" -ForegroundColor DarkYellow
		$CommandHistoryNumber = (Get-History | Select-Object -Last 1).Id
	}
 
	$cmd = Get-History -Id $CommandHistoryNumber -ErrorAction SilentlyContinue
	if ($cmd -ne $null)
	{
		$cmd.CommandLine | clip
		Write-Host "Copied the following command line to clip board:" -ForegroundColor Green
		Write-Host "	" $cmd.CommandLine -ForegroundColor Green
	}
}
Set-Alias -Name ccl -Value Copy-CommandLine
Start-Proc.ps1
function Start-Proc {   
param (   
        [string]$exe,# = $(Throw "An executable must be specified"),   
        [string]$arguments,   
        [switch]$hidden,   
        [switch]$waitforexit,
	[switch]$elevate
        )       
 
    # Build Startinfo and set options according to parameters  
    $startinfo = new-object System.Diagnostics.ProcessStartInfo   
    if ($elevate){$startinfo.Verb = "runas"}
    if ($exe){
		if (test-path $exe -pathType Container){
		$startinfo.FileName = 'powershell' 
		$startinfo.Arguments = "-NoExit -Command &{set-location '" + (resolve-path $exe) + "'}"
		}
    	else{
		$startinfo.FileName = $exe
		$startinfo.Arguments = $arguments  
		}
	}
	else {$startinfo.FileName = 'powershell'}
	if ($hidden){  
                $startinfo.WindowStyle = "Hidden"  
                $startinfo.CreateNoWindow = $TRUE  
                }  
    $process = [System.Diagnostics.Process]::Start($startinfo)  
    if ($waitforexit) {$process.WaitForExit()}  
}
Get-MyUser.ps1
function Get-MyUser
{
        $CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
	"UserSID = $($CurrentUser.User) ($($CurrentUser.Name))"
	"AuthenticationType = $($CurrentUser.AuthenticationType)" 
	"ImpersonationLevel = $($CurrentUser.ImpersonationLevel)"
	"Token = $($CurrentUser.Token)"
	"Groups = "
	foreach($Group in $CurrentUser.Groups)
	{
		"`tGroupSID = $Group ($($Group.Translate([System.Security.Principal.NTAccount])))"
	}
}
Pause.ps1
function Pause ($Message="Press any key to continue...")
{
	Write-Host -NoNewLine $Message
	$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
	Write-Host ""
}
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
powershell/basics/functions.txt · Last modified: 2017/02/23 14:49 by marcus