Quantcast
Channel: /r/powershell – How to Code .NET
Viewing all articles
Browse latest Browse all 8793

My POSH $Profile — Hope this helps someone out there.

$
0
0

This is going to be a beefy post — however, I have here my personal PowerShell $Profile that I use in my work domain. I am sharing this in hopes that it can help anyone else. I’ve researched and put together some extremely useful ‘tools’ for myself and co-workers — I’m no POSH expert but, I’m learning and these have made my life so much easier. Feel free to dig through the code and use what you want/can. I tried to comment generally on what most of these functions do but, I wasn’t 100% thorough.

I freely admit that I have yet to master error handling of any sort but, these do the tricks that I need on a daily basis and if/when errors occur I generally know why. (i.e. incorrect workstation, invalid pipeline inputs, human error)

Hope this helps someone!

# ------------------------------------- # IMPORT MODULES ---------------------- # ------------------------------------- import-module ActiveDirectory function PrintMenu{ Write-Host("List of Functions") Write-Host("-----------------") Write-Host("LastBoot [Param = list all computers]") Write-Host("Reboot [Param = list all computers]") Write-Host("Get-ScriptDirectory [no param returns current running directory]") write-host("") write-host("CommandType Name Function") write-host("----------- ---- --------") write-host("Alias adgroup Copy Specified User Groups to Clipboard") write-host("Alias chkuser Current Logged On User For Specified Workstation") write-host("Alias enac Enable User Account in AD") write-host("Alias getsam Search SAM Account Name By User Last Name") write-host("Alias godmode Access God Mode") write-host("Alias ghost Opens SCCM Ghost Session") write-host("Alias gpr Group Policy (Remote)") write-host("Alias huntuser Query SCCM For Last System Logged On By Specified User") write-host("Alias memcheck View RAM Statistics") write-host("Alias netmsg On-screen Message For Specified Workstation") write-host("Alias nithins Opens Nithin's SCCM Tool") write-host("Alias np Notepad++") write-host("Alias rdp Remote Desktop") write-host("Alias rmprint Clear Printer Drivers") write-host("Alias sccm Active Directory") write-host("Alias swcheck Check Installed Software For Specified Workstation") write-host("Alias sys All Remote System Info") write-host("") write-host("") }#End PrintMenu # ------------------------------------- # FUNCTIONS --------------------------- # ------------------------------------- #Undo cd command Remove-Item Alias:cd #Rebuild cd command to include '-' as an input -- used to move back to previous working directory function cd { if ($args[0] -eq '-') { $pwd=$OLDPWD;} else { $pwd=$args[0];} $tmp=pwd; if ($pwd) { #Enter Previous Working Directory when using cd - Set-Location $pwd;} Set-Variable -Name OLDPWD -Value $tmp -Scope global; } function Get-Latest { ((Invoke-WebRequest -Uri 'http://howtogeek.com').Links | Where-Object class -eq "title").Title } function getsam { Param([parameter(Mandatory = $true)]$UserLastName) #Get SAM Account Name for End User with Last Name search Get-ADUser -Filter "Surname -like '$UserLastName*'" | FT GivenName, SurName, SamAccountName } function huntuser { Param([parameter(Mandatory = $true)]$SamAccountName, #SCCM Site Name $SiteName="SITENAME", #SCCM Server Name $SCCMServer="SCCMSERVER") #SCCM Namespace $SCCMNameSpace="rootsmssite_$SiteName" #Query SCCM Server for list of workstations last logged on by specified SAM account name Get-WmiObject -namespace $SCCMNameSpace -computer $SCCMServer -query "select Name from sms_r_system where LastLogonUserName='$SamAccountName'" | select Name } function LastBoot { param( [Parameter(Mandatory=$true)] [string[]] $ComputerName) foreach ($Computer in $ComputerName) { New-Object psobject -Property @{ ComputerName = $Computer LastBootUpTime = [Management.ManagementDateTimeConverter]::ToDateTime( (Get-WmiObject -Class Win32_OperatingSystem -Computer $Computer | Select -Exp LastBootUpTime) ) } } }# Finish function function Reboot { param( [Parameter(Mandatory=$true)] [string[]] $ComputerName) foreach ($Computer in $ComputerName) { #Force reboot specified workstation or array restart-computer $Computer -Force } }# Finish function function ghost { param( [Parameter(Mandatory=$true)] [string]$computername) #Start 'Ghost' or interactive Remote Tools session with specified workstation - *Requires ActiveDirectory module and SCCM Start-Process 'C:Program Files (x86)Microsoft Configuration Manager ConsoleAdminUIbini386rc.exe' "1 $Computername" }#Finish function function rdp { param( [Parameter(Mandatory=$true)] [string]$computername) #Start Remote Desktop Protocol on specifed workstation & "C:windowssystem32mstsc.exe" /v:$computername /fullscreen }# Finish function function Get-ErrorInfo { & "C:Program Files (x86)Mozilla Firefoxfirefox.exe" https://www.google.com/search?q=$error[0].Exception }# Finish function function cl { #Clears screen (same as clear) but, writes created 'PrintMenu' back onto the main shell for function reference clear-host PrintMenu }# Finish function function godmode { #GodMode path based on current $env and current user $userpath = [environment]::getfolderpath("desktop") $godpath = "GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}" $finalpath = $userpath + $godpath if (!(Test-Path -Path $finalpath)) { #Creates GodMode path for current user New-Item -Type directory -Path $finalpath -force | out-null } #Opens GodMode path Start-Process "$finalpath" } function gpr { param( [Parameter(Mandatory=$true)] [string[]] $ComputerName) foreach ($Computer in $ComputerName) { #Opens (Remote) Group Policy for specified workstation gpedit.msc /gpcomputer: $Computer } }# Finish function function enac { $last = Read-Host -Prompt 'Search by Last Name' #Last Name search for Active Directory users - Gives you First, Last, & SAM Account Name Get-ADUser -Filter "Surname -like '$last*'" | FT GivenName,Surname,SamAccountName #Enter desired SAM Account Name to enable user account, if disabled Enable-ADAccount –Identity (Read-Host “Enter Desired Username”) write-host("") write-host("Specified Account Unlocked!") write-host("") }# Finish function function sys { param( [Parameter(Mandatory=$true)] [string[]] $ComputerName) write-host("") write-host("Gathering resources. Please wait...") write-host("") foreach ($Computer in $ComputerName) { #Gather specified workstation information $ComputerProgram = Get-WmiObject -class Win32_Product | Select-Object -Property Name | Sort-Object Name $computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer $computerBIOS = get-wmiobject Win32_BIOS -Computer $Computer $computerOS = get-wmiobject Win32_OperatingSystem -Computer $Computer $computerCPU = get-wmiobject Win32_Processor -Computer $Computer $computerHDD = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter drivetype=3 #Write all gathered workstation information to shell write-host "System Information for: " $computerSystem.Name -BackgroundColor DarkCyan "--------------------------------------------------------" "Last Reboot: " + $computerOS.ConvertToDateTime($computerOS.LastBootUpTime) "Operating System: " + $computerOS.OSArchitecture + " " + $computerOS.caption "Model: " + $computerSystem.Model "RAM: " + "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB) + "GB" "HDD Capacity: " + "{0:N2}" -f ($computerHDD.Size/1GB) + "GB" "HDD Space: " + "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size) + " Free (" + "{0:N2}" -f ($computerHDD.FreeSpace/1GB) + "GB)" "User Logged In: " + $computerSystem.UserName "--------------------------------------------------------" "" } }# Finish function function chkuser { param( [Parameter(Mandatory=$true)] [string[]] $ComputerName) write-host("") write-host("Gathering resources. Please wait...") write-host("") foreach ($Computer in $ComputerName) { $computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer Write-Host "User Logged Into $Computer : " $computerSystem.UserName Write-Host "" } }#Finish function <#function rmpro { #function works but, isn't perfected - Only keeping for reference for now $z = read-host -prompt("Workstation Name") $pro1 = Read-Host -prompt("Find Product Name Like") invoke-command -computername $z {wmic product where "name like '*$pro1*'" uninstall /nointeractive} }#> #Finish function function rmprint { param( [Parameter(Mandatory=$true)] [string]$computername) Try { $RemoteSession = New-PSSession -ComputerName $computername write-host "Removing printer drivers... Please wait..." } Catch { "Can't connect. Bad Workstation name, User name or Password. Aborting run." Break } Invoke-Command -Session $RemoteSession -ScriptBlock { # Removes print drivers, other than default image drivers if ((Test-Path -Path 'HKLM:SYSTEMCurrentControlSetControlPrintEnvironmentsWindows x64') -eq $true) { Remove-Item -PATH 'HKLM:SYSTEMCurrentControlSetControlPrintEnvironmentsWindows x64DriversVersion-3*' -EXCLUDE "*ADOBE*", "*MICROSOFT*", "*XPS*", "*REMOTE*", "*FAX*", "*ONENOTE*" -recurse Remove-Item -PATH 'HKLM:SYSTEMCurrentControlSetControlPrintPrinters*' -EXCLUDE "*ADOBE*", "*MICROSOFT*", "*XPS*", "*REMOTE*", "*FAX*", "*ONENOTE*" -recurse Set-Service Spooler -startuptype manual Restart-Service Spooler Set-Service Spooler -startuptype automatic } } Remove-PSSession $RemoteSession write-host "Closing PS session" }# Finish function <#function rmOffice { #Removes botched Office 2013 installations due to Programs and Features removal not working - Not something that all techs need access to - Keeping for future reference $ErrorActionPreference= 'silentlycontinue' $Workstation = (Read-Host -Prompt "Enter Workstation") Try { $RemoteSession = New-PSSession -ComputerName $Workstation } Catch { "Can't connect. Bad Workstation name, User name or Password. Aborting run." Break } Invoke-Command -Session $RemoteSession -ScriptBlock { New-PSDrive -PSProvider registry -root HKEY_CLASSES_ROOT -Name HKCR write-host "" write-host "Removing Microsoft Office 2013 registry and file components... Please Wait..." New-PSDrive -PSProvider registry -root HKEY_CURRENT_USER -Name HKCU | out-null remove-item -path 'C:Program Files (x86)Common Filesmicrosoft sharedOFFICE15' -force -recurse | out-null remove-item -path 'C:Program Files (x86)Common Filesmicrosoft sharedSource Engine' -force -recurse | out-null remove-item -path 'C:Program Files (x86)Microsoft OfficeOffice15' -force -recurse | out-null remove-item -path 'C:MSOCacheAll Users*0FF1CE}*' -force -recurse | out-null remove-item -path '*AppDataRoamingMicrosoftTemplates*.dotm' -force -recurse | out-null remove-item -path '*AppDataRoamingMicrosoftTemplates*.dotx' -force -recurse | out-null remove-item -path '*AppDatamicrosoftdocument building blocks*.dotx' -force -recurse| out-null remove-item -path 'HKCU:SoftwareMicrosoftOffice15.0' -recurse | out-null remove-item -path 'HKLM:SOFTWAREWow6432NodeMicrosoftOffice15.0' -recurse | out-null remove-item -path 'HKLM:SOFTWAREWow6432NodeMicrosoftOfficeDeliverySourceEngineDownloads*0FF1CE}-*' -recurse | out-null remove-item -path 'HKLM:SOFTWAREWow6432NodeMicrosoftWindowsCurrentVersionUninstall*0FF1CE*' -recurse | out-null remove-item -path 'HKLM:SYSTEMCurrentControlSetServicesose' -recurse | out-null remove-item -path 'HKCR:InstallerFeatures*F01FEC' -recurse | out-null remove-item -path 'HKCR:InstallerProducts*F01FEC' -recurse | out-null remove-item -path 'HKCR:InstallerUpgradeCodes*F01FEC' -recurse | out-null remove-item -path 'HKCR:InstallerWin32Asemblies*Office15*' -recurse | out-null remove-item -path 'HKLM:SOFTWAREWow6432NodeMicrosoftWindowsCurrentVersionUninstall*Office15*' -recurse| out-null write-host "" write-host "Object removal complete..."} Remove-PSSession $RemoteSession }#># Finish function function netmsg { #Network messaging is disabled on the domain - this is a workaround for the same type of results param([Parameter(Mandatory=$true)][string[]] $ComputerName) $ReadMe = read-host -prompt("Enter desired message") foreach($Computer in $ComputerName) { $g = $ReadMe #Invoke local MSG command on specified workstation - will generate pop-up message for any user logged onto that workstation - *Also shows on Login screen, stays there for 100,000 seconds or until interacted with invoke-command -computername $Computer { param($g) msg /time:100000 * "$g {NAME aka JBear| 5-1699 |Programmer/Systems Analyst}"} -argumentlist $g } }# Finish function function memcheck { #Get User Input & Initiate Remote Check param( [Parameter(Mandatory=$true)] [string]$computername) "Gathering resources..." invoke-command -computername $computername -scriptblock { #Top 10 Processes using RAM "" "Top 10 using the most RAM on $env:computername are:" $fieldproname = @{label = "Process"; Expression = {$_.name}; Align = "Left"}; $fieldramusage = @{label = "RAM Usage (MB)"; Expression = {[math]::round(($_.ws / 1mb), 2)}; Align = "Right"}; $prolist = get-process; $prolist | Sort-Object -Descending WS | Select-Object -First 10 | Format-Table $fieldproname,$fieldramusage -AutoSize; #Memory/VirtualMemory "Performance Statistics:" $fieldfreeram = @{label = "Available Physical Memory (GB)"; Expression = {[math]::round(($_.FreePhysicalMemory / 1mb), 2)}}; $fieldtotalram = @{label = "Total Physical Memory (GB)"; Expression = {[math]::round(($_.TotalVisibleMemorySize / 1mb), 2)}}; $fieldfreeVram = @{label = "Available Virtual Memory (GB)"; Expression = {[math]::round(($_.FreeVirtualMemory / 1mb), 2)}}; $fieldtotalVram = @{label = "Total Virtual Memory (GB)"; Expression = {[math]::round(($_.TotalVirtualMemorySize /1mb), 2)}}; $memtotal = Get-WmiObject -Class win32_OperatingSystem -ComputerName localhost; $memtotal | Format-List $fieldfreeram,$fieldtotalram,$fieldfreeVram,$fieldtotalVram; } } #Finish function function adgroup { param( [Parameter(Mandatory=$true)] [string[]] $Username) foreach ($Name in $UserName) { #Copies specified users' AD Groups to clipboard - created for specific person who needed this information Get-ADPrincipalGroupMembership $name | select name | clip} } function swcheck { param( [Parameter(Mandatory=$true)] [string[]]$computername) foreach ($computer in $computername) { #Collects installed software data and exports to CSV file - Possible to remove Export-CSV pipeline and just receive information in the shell Get-WmiObject -class win32_product -ComputerName $computer | Sort-Object Name | Select Name,InstallDate,Vendor,Version | Export-Csv "\SERVERTransferJBearSoftwareReport.csv" -NoTypeInformation -Force } } # ------------------------------------- # END FUNCTIONS ----------------------- <#$a = new-object -comobject wscript.shell $intAnswer = $a.popup("Do you want to run VMWare?", 0,"Run Program",4) If ($intAnswer -eq 6) { Start-Process "C:Program Files (x86)VMwareInfrastructureVirtual Infrastructure ClientLauncherVpxClient.exe"#> # ------------------------------------- # ------------------------------------- #setup window information # ------------------------------------- $Shell = $Host.UI.RawUI $size = $Shell.BufferSize $size.width=150 $size.height=5000 $Shell.BufferSize = $size $size = $Shell.WindowSize $Shell.WindowSize = $size #$shell.BackgroundColor = “DarkGray” #$shell.ForegroundColor = “Cyan” # ------------------------------------- # Set the script location # ------------------------------------- Update-Help Clear-Host #Get-Latest #Set-ExecutionPolicy RemoteSigned set-location \SERVERTransferJBearScripts # ------------------------------------- # Display Functions to run # ------------------------------------- Write-Host("List of Functions") Write-Host("-----------------") Write-Host("LastBoot [Param = list all computers]") Write-Host("Reboot [Param = list all computers]") Write-Host("Get-ScriptDirectory [no param returns current running directory]") # ------------------------------------- # Set program alias # ------------------------------------- new-item alias:np -value "\SERVERTransferJBearscriptsNotepad++notepad++.exe" new-item alias:psi -value C:Windowssystem32WindowsPowerShellv1.0PowerShell_ISE.exe new-item alias:vmware -value "C:Program Files (x86)VMwareInfrastructureVirtual Infrastructure ClientLauncherVpxClient.exe" new-item alias:vs -value "C:Program Files (x86)Microsoft Visual Studio 10.0Common7IDEdevenv.exe" new-item alias:toad -value "C:ToadQuest SoftwareToad for Oracle 10.5Toad.exe" new-item alias:sccm -value "C:UsersPublicDesktopadminconsole.msc" new-item alias:nithins -value "C:UsersDewittJDesktopNithins.hta" clear-host PrintMenu # ------------------------------------- # Programs to start # ------------------------------------- <# $a = new-object -comobject wscript.shell $intAnswer = $a.popup("Do you want to run VMWare?", 0,"Run Program",4) If ($intAnswer -eq 6) { Start-Process "C:Program Files (x86)VMwareInfrastructureVirtual Infrastructure ClientLauncherVpxClient.exe" } $intAnswer = $a.popup("Do you want to run Visual Studio 2010?", 0,"Run Program",4) If ($intAnswer -eq 6) { Start-Process "C:Program Files (x86)Microsoft Visual Studio 10.0Common7IDEdevenv.exe" } $intAnswer = $a.popup("Do you want to run Toad?", 0,"Run Program",4) If ($intAnswer -eq 6) { Start-Process "C:ToadQuest SoftwareToad for Oracle 10.5Toad.exe" } $intAnswer = $a.popup("Do you want to run AD Admin MMC?", 0,"Run Program",4) If ($intAnswer -eq 6) { Start-Process "C:ScriptsAdmin MMC.msc" } #> <# # ------------------------------------- # Button Types # ------------------------------------- Value Description ----------------------------------------------- 0 Show OK button. 1 Show OK and Cancel buttons. 2 Show Abort, Retry, and Ignore buttons. 3 Show Yes, No, and Cancel buttons. 4 Show Yes and No buttons. 5 Show Retry and Cancel buttons. #> 

submitted by /u/JBear_Alpha
[link] [comments]

The post My POSH $Profile — Hope this helps someone out there. appeared first on How to Code .NET.


Viewing all articles
Browse latest Browse all 8793

Trending Articles