My PS $Profile

<

pre>Hi guys,

I’ve seen everyone sharing their PowerShell Profile recently, so I thought I’d do the same. This includes a number of interesting little functions I’ve made, and that I’ve seen from others online.

My favorite part is that I stole some formatting ideas from the Exchange Cmdlets for PowerShell, so when you launch this, it looks like this:profile

I hope you’re able to copy or enjoy some of this stuff.


###Search-Google############################################################
<#
.Synopsis
   Searches the Googes
.DESCRIPTION
   Lets you quickly start a search from within Powershell
.EXAMPLE
   Search-Google Error code 5
   --New google search results will open listing top entries for 'error code 5'

.EXAMPLE
   search-google (gwmi win32_baseboard).Product maximum ram

   If you need to get the maximum ram for your motherboard, you can even use this
   type of syntax
#>
function Search-Google
{
  
    
    Begin
    {
    $query='https://www.google.com/search?q='
    }
    Process
    {
    Write-Host $args.Count, "Arguments detected"
    "Parsing out Arguments: $args"
    for ($i=0;$i -le $args.Count;$i++){
    $args | % {"Arg $i `t $_ `t Length `t" + $_.Length, " characters";$i++} }
        
    
    $args | % {$query = $query + "$_+"}
    $url = "$query"
    }
    End
    {
    $url.Substring(0,$url.Length-1)
    "Final Search will be $url"
    "Invoking..."
    start "$url"
    }
}

###Helper Functions############################################################

Function Uptime{
param([parameter(Mandatory=$false)][string]$computer=".")
#$computer = read-host "Please type in computer name you would like to check uptime on"

$lastboottime = (Get-WmiObject -Class Win32_OperatingSystem -computername $computer).LastBootUpTime

$sysuptime = (Get-Date) – [System.Management.ManagementDateTimeconverter]::ToDateTime($lastboottime)
 
Write-Host "$computer has been up for: " $sysuptime.days "days" $sysuptime.hours "hours" $sysuptime.minutes "minutes" $sysuptime.seconds "seconds"}

Function diskusage
{
param([parameter(Mandatory=$false)][string]$remotepc=".")
#$remotepc = Read-host 'For which computer?'
Get-WmiObject win32_logicaldisk -ComputerName $remotepc  -Filter "drivetype=3" | select SystemName,DeviceID,VolumeName,@{Name="Size(GB)";Expression={"0:N1}" -f($_.size/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}}}

Function patches{ 
param([parameter(Mandatory=$false)][string]$remotepc=".")
#$remotepc = Read-host 'For which box?'
Get-WmiObject -Class "win32_quickfixengineering" -ComputerName $remotepc | select hotfixid,installedon}


function Play-Bubble{
[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        $bubbles="0"
)

$sound = new-Object System.Media.SoundPlayer;
$sound.SoundLocation = "C:\users\sowen\Downloads\bubble_Pop-Sound_Explorer-1206462561.wav"

 1..[int]$bubbles | % {$sound.Play();start-sleep -Milliseconds 150}
}

###Get-SwitchedStatus############################################################

####################################################################
#     ----Name : Work Client Quest Switch Status 
#     ---Author: Stephen Owen, Work, 7.24.2014
#     Function : Use this tool to determine if a user account has switched or not, based on the account's Source targetAddress property
#     ---Usage : Get-SwitchedStatus <$username>


Function Get-SwitchedStatus {
<#
    .Synopsis
       Use this tool to determine if a user account has switched or not, based on the account's Source targetAddress property
    .DESCRIPTION
       This tool connects to the Source (legacy) AD Domain and looks up the specified user object, returning the .targetAddress property
       connects to the target domain to move the user account to the correct OU
    .PARAMETER UserName
       <Mandatory> Specify the username to inquire
    .EXAMPLE
       Get-SwitchedStatus -UserName Stephen.Owen 
       > This tool will connect to the source, and grab the targetAddress property of the object <Stephen.Owen>.  If this contains *@source.qmm, the account is most likely unSwitched.  If this value contains *@target.qmm, then the account is most likely Switched.
    .EXAMPLE
       "Stephen.Owen","Mark.Wuerslin" | ForEach-Object {Get-SwitchedStatus -UserName $_})
       > Perform Get-SwitchedStatus on both Stephen.Owen, then Mark.Wuerslin
#>
[CmdletBinding()]
param([Alias("UserName","LogonName")][parameter(Mandatory=$True,ValueFromPipeline=$True,position=0)][string[]]$UserNames,[string]$service="amatldc01",[switch]$WriteWarning)
 #Write-host "Checking for Quest Active Roles PSSnapIn..." -ForegroundColor White -NoNewline
      $obj=@()
      $Host.UI.RawUI.WindowTitle="---Get UserSwitchedStatus Tool"
      Write-Progress -Activity ("Checking for Quest Active Roles PSSnapIn...") -PercentComplete 25  -Status "Connecting"   
            if (-not ((Get-PSSnapin).Name -contains "Quest.ActiveRoles.ADManagement")){
                
                try  {Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction Stop}
                catch{
                      #Write-host "[ERROR]" -ForegroundColor Red
                      Write-Warning "This tool depends on the Quest Active Roles tools to operate" 
                      $DL = Read-Host "Download? Y/N"
                      IF ($DL -eq "Y"){
                        Start 'http://www.quest.com/quest_download_assets/individual_components/Quest_ActiveRolesManagementShellforActiveDirectoryx86_151.msi'
                        "Exiting..."
                        }
                        ELSE{"Exiting...";break}

                      BREAK
                      }
               finally{#Write-Host "[OKAY]" -ForegroundColor Green 
                      }
            }
        ELSE{start-sleep -Milliseconds 150
             #Write-Host "[OKAY]" -ForegroundColor Green
             Write-Progress -Activity ("Checking for Quest Active Roles PSSnapIn...") -PercentComplete 50   
            }
            if (-not($credential)){
                $credential= Get-Credential -Message "Enter credentials which can browse AD in Source and Target"}ELSE{"Cached credential detected, continuing..."
                }
        Write-host ("Detected: " + $UserNames.Count + " objects")
           #Connect to source 
            start-sleep -Milliseconds 150
            #Write-Host "Connecting to Source..." -NoNewline
            Write-Progress -Activity ("Connecting to source...") -PercentComplete 50  -Status "Connecting..."
            try  {Connect-QADService $service -Credential $credential -ErrorAction Stop}
            Catch{
                 Write-warning "Error ocurred connecting to AMATLDC01 to pull source OU paths, check credentials..."
                 BREAK
                 }
          finally{#Write-Host "[OKAY]" -ForegroundColor Green 
          }
    forEach ($CurrentObject in $UserNames){
        Try  {start-sleep -Milliseconds 150
              Write-Progress -Activity ("Looking up $CurrentObject on $service") -PercentComplete 75 -Status "Gathering Info..."
              $user = get-qaduser $CurrentObject -DontUseDefaultIncludedProperties -IncludedProperties targetAddress -Service $service -ConnectionAccount $credential.UserName -ConnectionPassword $credential.Password -ErrorAction Stop 
              Write-Debug "Troubleshoot `$user"}

       catch {Write-Warning ("Unable to perform Get-QADUser for object $CurrentObject from service: $service `n check `$CurrentObject")
             }
             Write-Debug "Troubleshoot `$user"

        if ($user){
            if (-not($user.targetAddress)){
                if ($WriteWarning){
                    Write-Warning ("Unable to find targetAddress: $CurrentObject has NOT Switched")
                    }
                  
                  }
            }

        if ($user.targetAddress -like "*@target.qmm"){
            $obj += [pscustomobject]@{UserName=$user;Status="Switched"}
            CONTINUE
            }
            if ($user.Email){
                $obj += [pscustomobject]@{UserName=$user;Status="Not Switched"}
                }
            ELSE{
                $obj += [pscustomobject]@{UserName=$user;Status="No E-mail"}
                }
        }

        $obj | ft
}

####Split-n-Trim#########################################################################

Function Split-N-Trim {
param(
      [Parameter(Mandatory=$True,ValueFromPipeline=$True)][string[]]$Objects
      )
      write-host ("-Recieved " + $Objects.Count +" objects")
      $Objects = $Objects.Trim().Split("`n")
      write-host ("Returning " + $Objects.Count +" objects")
      Return $Objects
}

new-alias Trim-N-Split Split-N-Trim


####Move-ClientUsers#########################################################################

####################################################################
#     ----Name : Work Client User Moving tool
#     ---Author: Stephen Owen, Work, 7.23.2014
#     Function : Post User-Migration, moves users to the correct OU
#     ---Usage : Use to ensure that users are placed in the right OU

Function Move-ClientUsers{
<#
    .Synopsis
       Use this tool Post User-Migration, to moves users to the correct OU.  Supports -WhatIf for verification!
    .DESCRIPTION
       This tool connects to the Source (legacy) AD Domain and looks up all user objects found within a source file.  It then stores a record of the correct OU, and then 
       connects to the target domain to move the user account to the correct OU
    .PARAMETER UserList
       Specify the path to a 'User Migration.txt' file which contains user names. Mandatory parameter.
    .SWITCH ShowVerbose
       Use this switch to recieve Verbose output as the function executes.
    .SWITCH ListOUs
        Use this switch to see a listing of User's Target and Source OUs
    .EXAMPLE
       Move-ClientUsers -UserList '.\2014-07-22_20-13-48 M2 - User Migration.txt' 
       > This tool will enumerate the contents of '.\2014-07-22_20-13-48 M2 - User Migration.txt', omitting the first line, then connect to the source domain to retrieve each User's Object location.  Next, the process will connect to the target to verify the object location there.  If the values do not match, then the tool will move the object to the correct location.  
    .EXAMPLE
       Move-ClientUsers -UserList '.\2014-07-22_20-13-48 M2 - User Migration.txt' -WhatIf
       > Receive Standard PowerShell WhatIf output, useful to know the scope of an action
#>
[CmdletBinding(SupportsShouldProcess=$true)]
 Param(
    [Parameter(Mandatory=$false,Position=0,HelpMessage="Please specify the users to be moved to the appropriate OUs.  This can be either names within a file, or a hashtable.")]
            [string[]]$UserList,
            [string[]]$ADRoot,
            [switch]$ShowVerbose, #Work-around support to enable lazy verbose output
            [switch]$ListOUs
            
            )
begin{
            Write-host "Checking for Quest Active Roles PSSnapIn..." -ForegroundColor White -NoNewline
                
            try  {Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction Stop}
            catch{
                  Write-host "[ERROR]" -ForegroundColor Red
                  Write-Warning "This tool depends on the Quest Active Roles tools to operate" 
                  $DL = Read-Host "Download? Y/N"
                  IF ($DL -eq "Y"){
                    Start 'http://www.quest.com/quest_download_assets/individual_components/Quest_ActiveRolesManagementShellforActiveDirectoryx86_151.msi'
                    "Exiting..."
                    }
                    ELSE{"Exiting...";break}

                  BREAK
                  }
           finally{Write-host "[OKAY]" -ForegroundColor Green }

           if (-not($credential)){
                $credential= Get-Credential -Message "Enter credentials which can browse AD in Source and Target"}ELSE{"Cached credential detected, continuing..."
                }

           if ($ADRoot){

                #Connect to Target
                Write-host "Connecting to Target to enumerate $ADRoot members..." -NoNewLine
                try  {
                    Connect-QADService amatlds01 -Credential $credential -ErrorAction Stop | Out-Null
                     }
                catch{
                     Write-warning "Error ocurred connecting to AMATLDS01 to pull source OU paths, check credentials..."
                     BREAK
                     }
              finally{Write-Host "[OKAY]" -ForegroundColor Green}
            
               $InputObjects = get-qaduser -SearchRoot $ADRoot | select -ExpandProperty Name
               }
               ELSE{

                if ($Userlist -like "*User*"){$ListContainsUserObjects=$TRUE}
                #Flow, get users from migration file
                $InputObjects = Get-Content $UserList
                #Dump first line
                $InputObjects = $InputObjects[1..$InputObjects.Count]
                $InputObjects = $InputObjects | % {if ($_ -notlike "*#MULTIPLE_SEE_NOTES#$"){$_}}
            }

            $UsersArray = New-Object -TypeName System.Collections.ArrayList
            
            

            #Connect to source 
            Write-host "Connecting to Source..." -NoNewline
            try  {Connect-QADService amatldc01 -Credential $credential -ErrorAction Stop | Out-Null}
            Catch{
                 Write-warning "Error ocurred connecting to AMATLDC01 to pull source OU paths, check credentials..."
                 BREAK
                 }
          finally{Write-host "[OKAY]" -ForegroundColor Green }
            
            
            #Flow, get user DN from source org
            #we want ParentContainer
            $i = 0;$x = $i
            ForEach ($user in $InputObjects){
                Write-Progress -Activity ("Retrieving Source DN for $user") -PercentComplete (($i/($InputObjects.count)*100 ))
                if ($user -eq "#MULTIPLE_SEE_NOTES#$"){BREAK}
                IF ($ListContainsUserObjects){$DN = get-QADUser $user | Select -ExpandProperty ParentContainer}
                    ELSE{$DN = get-QADComputer $user | Select -ExpandProperty ParentContainer}

                Write-Debug "Debug Breakpoint to test ParentContainer for Source"

                $obj = [pscustomobject]@{index=$i;UserName=$user;SourceContainer=$DN;TargetContainer=$null;Match=$false} 
        
                $UsersArray.Add($obj) | out-null
                $i++
                }

            if ($ShowVerbose){$UsersArray | Select-Object UserName,SourceContainer}
            $users = "add DN"
            
            #Connect to Target
            Write-host "Connecting to Target..." -NoNewLine
            try  {
                Connect-QADService amatlds01 -Credential $credential -ErrorAction Stop | Out-Null
                 }
            catch{
                 Write-warning "Error ocurred connecting to AMATLDS01 to pull source OU paths, check credentials..."
                 BREAK
                 }
          finally{Write-Host "[OKAY]" -ForegroundColor Green}
            #Flow, move users in target to appropriate location 

            ForEach ($user in $UsersArray){
                
                Write-Progress -Activity ("Retrieving Target DN for " + $user.UserName) -PercentComplete (($x/($UsersArray.count)*100 ))
                if ($user -eq "#MULTIPLE_SEE_NOTES#$"){BREAK}
                IF ($ListContainsUserObjects){$DN = get-QADUser $user.UserName | Select -ExpandProperty ParentContainer}
                    ELSE{$DN = get-QADComputer $user.UserName | Select -ExpandProperty ParentContainer}
                
                #Get Current Location in Target
                #$DN = get-QADUser $user.UserName | Select -ExpandProperty ParentContainer

                Write-Verbose ("Current object: "+ $user.UserName  +" `n`t Current Index $x Index based user name = " + $UsersArray[$x].UserName)
                
                #Set the TargetContainer value both for the current object in ForEach and also the outer object in $UsersArray
                $user.TargetContainer = $DN 
                $UsersArray[$x].TargetContainer = $DN 

                $UsersArray[$x].Match = If (($user.SourceContainer -replace 'Clientad.Client.com','Client.com')-match $user.TargetContainer){$TRUE}ELSE{$FALSE}

                Write-Debug "Breakpoint: within ForEach loop in Target, use this to test comparison logic to see if user is in appropriate OU"
                if ($ShowVerbose){$User.SourceContainer,$user.TargetContainer}
                
                $x++

            }
            
            if ($ShowVerbose){$UsersArray |  Select-Object UserName,SourceContainer,TargetContainer,@{Name='Match';Expression={If (($_.SourceContainer -replace 'Clientad.Client.com','Client.com')-match $_.TargetContainer){$TRUE}ELSE{$FALSE}} } | Format-Table -AutoSize}
            Write-Debug "Breakpoint: Test comparison of Source & Target"
}            
            process{
                
                
                        $y = 1   
                        ForEach ($user in ($UsersArray | ? {($_.SourceContainer)} | ? Match -eq $false)){
                            if ($user -eq "#MULTIPLE_SEE_NOTES#$"){BREAK}
                            if($PSCmdlet.ShouldProcess($User.UserName,"Move object to '$($User.SourceContainer)'")){
                                Write-Progress -Activity ("Attempting to move " + $user.UserName) -PercentComplete (($y/($UsersArray.count)*100 )) -Status "Moving..."
                                $newTargetOU = (($user.SourceContainer -replace 'Clientad.Client.com','Client.com'))
                                    if ($newTargetOU -like "*/Clean Sweep"){
                                        "Clean sweeper detected, mitigating..."
                                        $newTargetOU = $newTargetOU -replace "/Clean Sweep",""
                                        }
                                 Write-host ("Preparing to move: " + $user.UserName) -NoNewline 
                                try {Get-QADUser $user.UserName| Move-QADObject -NewParentContainer $newTargetOU -ErrorAction Stop}
                               catch{Write-debug "Troubleshooting..."}
                             finally{Write-host -ForegroundColor Green "`t`t`t[OKAY]"}
                               }
                               $y++
                       } 
                If ($ListOUs){return $UsersArray}    
                }
           } 
            #return $UsersArray
            #$Global:UsersArray = $UsersArray


###Remind-Me Functions + Welcome Text############################################################

function RemindMe-Comparators {

$writeout = @"
Windows PowerShell includes the following comparison operators:

  -eq
  -ne
  -gt
  -ge
  -lt
  -le
  -Like
  -NotLike
  -Match
  -NotMatch
  -Contains
  -NotContains
  -In
  -NotIn
  -Replace
"@

"$writeout"

}

function RemindMe-Git{
$giturl = "https://github.com/feelingsofwhite/MaximumPower"


$nav = Read-host "Navigate to Azure?"
if ($nav -eq 'Y')
{$ie.visible = $true}
#"Chxda7izL3GR" | clip
}

$custom = @"
--Custom Commands Available--
 RemindMe-Azure`t`tDisplay Reminder information for Azure
 RemindMe-Comparators`tDisplay Reminder information on Comparison Operators
 RemindMe-Git`t`tDisplay Remind information on how to use Git
 Search-Google`t`tQuickly Launch a google Search
 Play-Bubbles`t`tPop `dem Bubbles!
 Get-SwitchStatus`tSee the status of users
 Split-N-Trim`t`tSplit input on a new-line character and trim spaces
 Trim-N-Split`t`tThe same as above, but reversed
 Move-ClientUser`tMove User Accounts
 Uptime`t`t`t`tEasily get Uptime
 DiskUsage`t`t`tEasily Get Disk Usage
 Patches`t`t`tLists Patches
"@

Write-Host -fore Yellow -Back Black $custom

###Setup Env, import modules, change dirs############################################################

if (Test-path "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\"){
	Write-Host "Azure Modules found, importing"
	gci 'C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure' *.psd1 | select -ExpandProperty Fullname| Import-module -PassThru
	}
	ELSE
	{#Write-Warning "Azure and Azure Platform Modules not detected, skipping..."
}



if (Test-path "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"){
	import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1" -PassThru
	}
	ELSE
	{#Write-Warning "Config Manager PowerShell module not detected, skipping..."
		}


if (test-path C:\Users\sowen\dropbox\docs\Work\Client\Scripts){"`nClient Scripts Directory detected, must be using the work laptop, navigating to project scripts dir...";Set-location "C:\Users\sowen\dropbox\docs\Work\Client\Scripts"}

cls

###Display Welcome############################################################

Write-Host -fore Yellow -Back Black $custom
Write-host ("`n Online with PowerShell Version:" + (get-host | select -expand Version))

Advertisements

Have a code issue? Share your code by going to Gist.github.com and pasting your code there, then post the link here!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s