├── AD_user_info.ps1 ├── ConvertFrom-DHCP.ps1 ├── GAL_cleanup.ps1 ├── Get-HotfixInfo.ps1 ├── Get-ISPInfo.ps1 ├── Get-MostLogins.ps1 ├── Get-Uptime.ps1 ├── Invoke-ChatGPTQuestion.ps1 ├── LocalGroupRights.psm1 ├── Microsoft.PowerShell_profile.ps1 ├── Mirror_AD_Groups.ps1 ├── PS_GUI_AD_Real_Name_Finder.ps1 ├── PoshWunderlist.psm1 ├── README.md ├── Remove-ItemByDate.ps1 ├── Remove-qBtorrent.ps1 ├── Set-RedditWallPaper.ps1 ├── ad_unix_attributes.ps1 ├── apostrophes.ps1 ├── azure-pipelines.yml ├── bing_rewards.ps1 ├── bulk_password.ps1 ├── change_sip_ocs.ps1 ├── check_suspended.ps1 ├── copy_security_groups.ps1 ├── create_admin_account.ps1 ├── delete_user_folders.ps1 ├── dns_a_records.ps1 ├── empty_ou.ps1 ├── exchange_db_status.ps1 ├── file_date_and_size.ps1 ├── file_migration.ps1 ├── find_local_admins.ps1 ├── find_os.ps1 ├── find_user_groups.ps1 ├── folder_permissions.ps1 ├── gce_vm.ps1 ├── home_zestimate.ps1 ├── idrac_cim_job.ps1 ├── install_applications_wmi.ps1 ├── leech.ps1 ├── local_admin_users.ps1 ├── local_security_policy_update.ps1 ├── logon.ps1 ├── monitor_dns_changes.ps1 ├── move_ou_by_os.ps1 ├── optional_features.ps1 ├── ping_dns_name.ps1 ├── ps_googlemap_route.ps1 ├── ps_prompt.ps1 ├── pushbullet.ps1 ├── remove_dns.ps1 ├── remove_local_admin_domain_users.ps1 ├── remove_manager.ps1 ├── remove_null_groups.ps1 ├── remove_rename_unjoin.ps1 ├── remove_user_session.ps1 ├── samaccount_from_real_name.ps1 ├── signature.ps1 ├── terminated_user.ps1 ├── test.ps1 ├── test_questions.psm1 ├── update_dfsn_fqdn.ps1 ├── userlogin_query.ps1 └── vm_hdd_resize.ps1 /AD_user_info.ps1: -------------------------------------------------------------------------------- 1 | #This script will find users in AD with email address like @contoso.com, print out specific properties in this case displayname 2 | #mailm street adddress, OfficePhone, MobilePhone, then export this to a CSV 3 | 4 | $searchBase = 'ou=users,ou=resources,dc=contoso,dc=local' 5 | 6 | Foreach ($user in (Get-ADUser -filter {mail -like '*@contoso.com'} -SearchBase $searchBase)){ 7 | Get-ADUser -Identity $user -Properties Displayname, Mail, StreetAddress, OfficePhone, MobilePhone | 8 | select Displayname, Mail, StreetAddress, OfficePhone, MobilePhone | 9 | Export-Csv -Path C:\Users\admin\Desktop\contoso_users.csv -Append 10 | } 11 | -------------------------------------------------------------------------------- /ConvertFrom-DHCP.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Converts a Windows DHCP address to static 4 | .DESCRIPTION 5 | Using only PowerShell convert a number to CIDR notation 6 | .EXAMPLE 7 | Get-NetIPConfiguration -InterfaceAlias 'vEthernet (external)' | ConvertFrom-DHCP 8 | .PARAMETER InterfaceAlias 9 | The alias of the interface that is to be set to static. 10 | #> 11 | 12 | Function ConvertFrom-DHCP { 13 | [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] 14 | 15 | param( 16 | [parameter(ValueFromPipelineByPropertyName)] 17 | [string]$InterfaceAlias 18 | ) 19 | $interface = Get-NetIPConfiguration -InterfaceAlias $InterfaceAlias 20 | $dns = (Get-DnsClientServerAddress -InterfaceAlias $InterfaceAlias -AddressFamily IPv4).ServerAddresses 21 | #Output 22 | $new_ip_splat = @{ 23 | interfacealias = $interfacealias 24 | ipaddress = $interface.ipv4address.ipv4address 25 | defaultgateway = $interface.ipv4defaultgateway.nexthop 26 | PrefixLength = $((Get-NetIPAddress -InterfaceAlias $interface.InterfaceAlias -AddressFamily IPv4).PrefixLength) 27 | } 28 | if ($PSCmdlet.ShouldProcess(($new_ip_splat.GetEnumerator() | ForEach-Object { "{0}`t{1}" -f $_.Name, ($_.Value -join ", ") }))) { 29 | Remove-NetIPAddress -InterfaceAlias $interfacealias -AddressFamily ipv4 30 | New-NetIPAddress @new_ip_splat 31 | Set-DnsClientServerAddress -InterfaceAlias $interfacealias -ServerAddresses $dns 32 | } 33 | else { 34 | exit 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /GAL_cleanup.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | This script looks for accounts in AD that are disabled, then checkes Exchange to see if the account is still visable 4 | in the GAL. 5 | 6 | .SYNTAX 7 | Gal_cleanup.ps1 [-Remove] 8 | 9 | .EXAMPLE 10 | -------------------------- EXAMPLE 1 -------------------------- 11 | PS C:\>create_admin_account.ps1 12 | 13 | This will show all accounts that are disabled in AD but still visable in the GAL. 14 | 15 | -------------------------- EXAMPLE 2 -------------------------- 16 | PS C:\>create_admin_account.ps1 -remove 17 | 18 | This will remove all accounts that are disabled in AD but still visable in the GAL. 19 | 20 | 21 | 22 | #> 23 | [CmdletBinding()] 24 | param([switch] $Remove) 25 | 26 | function GAL_Cleanup{ 27 | 28 | foreach($user in (Get-ADUser -Properties * -Filter {Enabled -eq $false})){ 29 | try{ 30 | if(((get-Mailbox $($user.SamAccountName) -ErrorAction Stop).HiddenFromAddressListsEnabled) -eq $false){ 31 | 32 | Write-Verbose "Creating custom object" 33 | New-Object -TypeName PSCustomObject -Property @{ 34 | SAMAccoutName = $user.samaccountname 35 | Name = $user.name 36 | 37 | } 38 | 39 | if($remove){ 40 | Set-Mailbox $user.SamAccountName -HiddenFromAddressListsEnabled $true 41 | Write-Output "$($user.SamAccountName) has been removed from the GAL" 42 | } 43 | } 44 | } 45 | 46 | catch { 47 | Write-Error "There is no mailbox for $($user.DisplayName)" 48 | 49 | } 50 | 51 | } 52 | } 53 | 54 | GAL_Cleanup 55 | -------------------------------------------------------------------------------- /Get-HotfixInfo.ps1: -------------------------------------------------------------------------------- 1 | # This script aims to give more detail than the Get-Hotfix. In particular this shows install status and an accurate install date. 2 | function Get-HotfixInfo { 3 | $Session = New-Object -ComObject "Microsoft.Update.Session" 4 | $Searcher = $Session.CreateUpdateSearcher() 5 | $historycount = $Searcher.GetTotalHistoryCount() 6 | $Searcher.QueryHistory(0, $historycount) | Select-Object Title, Description, Date, 7 | @{ name = "Operation"; expression = { switch ($_.operation) { 8 | 1 { "Installation" }; 2 { "Uninstallation" }; 3 { "Other" }; 9 | } 10 | } 11 | }, 12 | @{name = "Result"; expression = { switch ($_.ResultCode) { 13 | 0 { "Not Started" }; 1 { "In Progress" }; 2 { "Succeeded" }; 3 { "Succeeded With Errors" }; 4 { "Failed" }; 5 { "Aborted" }; default { "Unknown" } 14 | } 15 | } 16 | } , 17 | @{name = "HotFixID"; expression = { 18 | $_.title -match "\bKB[0-9]*\b" | Out-Null 19 | $($Matches.Values) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Get-ISPInfo.ps1: -------------------------------------------------------------------------------- 1 | #This script uses will give you some information of your ISP 2 | Invoke-RestMethod -Uri http://ip-api.com/json/$((Invoke-RestMethod -Uri 'https://api.ipify.org?format=json').ip) 3 | -------------------------------------------------------------------------------- /Get-MostLogins.ps1: -------------------------------------------------------------------------------- 1 | function Get-MostLogins { 2 | <# 3 | .SYNOPSIS 4 | Finds all domain machines a user has logged into by using the users 'real' name 5 | 6 | .DESCRIPTION 7 | This script uses my user login script log and finds 8 | what machine the user logs into most. In my environment users log into several machines, this makes finding their primary 9 | machine much easier. I will use this script in subsequent scripts to auto find the users primary machine and preform an 10 | action. 11 | 12 | I've added the ablity to choose either a file that contains a list of users to find most logins or one user 13 | I've also added a fix for users with apostrophe's in their name 14 | 15 | .PARAMETER Name 16 | Searches a single user by their 'real' name 17 | 18 | .PARAMETER File 19 | Takes a text file with a list of users 'real' names and queries them with this script. You must specify full path to file 20 | 21 | .PARAMETER Full 22 | Lists all the machines a user has logged into 23 | 24 | .EXAMPLE 25 | Get-MostLogins -Name "Joe Rodriguez" 26 | This command will show what machine Joe Rodriguez logged into the most 27 | 28 | .EXAMPLE 29 | Get-MostLogins -File c:\users\joerod\desktop\users.txt 30 | This command will show what machine all the users in the text file users.txt logged into the most 31 | 32 | .EXAMPLE 33 | Get-MostLogins -Name "Joe Rodriguez" -Full 34 | This command will show all machines Joe Rodriguez logged into 35 | 36 | #> 37 | 38 | 39 | [CmdletBinding(DefaultParameterSetName="Name")] 40 | param( 41 | [Parameter(Position=0, ParameterSetName="File")] 42 | [string] 43 | $File, 44 | 45 | [Parameter(Position=0, ParameterSetName="Name")] 46 | [string] 47 | $Name, 48 | 49 | [switch]$Full 50 | ) 51 | 52 | if ($psCmdlet.ParameterSetName -eq "File") { 53 | foreach($name in gc $file){ 54 | #if name has an apostrophe 55 | if($name.Contains("'")){ 56 | $name = ($name.replace("'","''")) 57 | } 58 | 59 | try{ 60 | 61 | foreach($user in (Get-ADUser -Properties * -Filter "Name -like '$Name*'" -ErrorAction Stop | ? {$_.Enabled -contains "True"})){ 62 | $array = Import-Csv \\Path\to\Share\Logon.log | ? {$_.username -eq $user.samaccountname} | % { 63 | 64 | New-Object -TypeName PSCustomObject -Property @{ 65 | Name = $user.name 66 | SAMAccoutName = $user.samaccountname 67 | ComputerName = $_.computername 68 | } 69 | } 70 | if($full){ 71 | $array 72 | } 73 | 74 | else{ 75 | $array | sort | group ComputerName | sort Count | select -ExpandProperty Group | select -last 1 76 | } 77 | } 78 | } 79 | 80 | catch{ 81 | Write-Warning "Cannot find $name" 82 | 83 | } 84 | } 85 | } 86 | 87 | else { 88 | 89 | #if name has an apostrophe 90 | if($name.Contains("'")){ 91 | $name = ($name.replace("'","''")) 92 | } 93 | 94 | try{ 95 | 96 | foreach($user in (Get-ADUser -Properties * -Filter "Name -like '$Name*'" | ? {$_.Enabled -contains "True"})){ 97 | $array = Import-Csv \\Path\to\Share\Logon.log | ? {$_.username -eq $user.samaccountname} | % { 98 | 99 | New-Object -TypeName PSCustomObject -Property @{ 100 | Name = $user.name 101 | SAMAccoutName = $user.samaccountname 102 | ComputerName = $_.computername 103 | } 104 | } 105 | if($full){ 106 | $array 107 | } 108 | 109 | else{ 110 | $array | sort | group ComputerName | sort Count | select -ExpandProperty Group | select -last 1 111 | } 112 | } 113 | } 114 | catch{ 115 | Write-Warning "Cannot find $name" 116 | 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /Get-Uptime.ps1: -------------------------------------------------------------------------------- 1 | #I wrote this script as a Powershell clone to the Linux "uptime" application 2 | 3 | Function Get-Uptime($Computer = $env:COMPUTERNAME){ 4 | $date = Get-Date -Format HH:mm:ss 5 | $lastbootuptime = Get-WmiObject win32_operatingsystem -ComputerName $Computer 6 | $uptime = [datetime]::Now – $lastbootuptime.ConverttoDateTime($lastbootuptime.lastbootuptime) 7 | $usercount = (Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer | Select -ExpandProperty Antecedent -Unique).count 8 | Write-Output ("{0} up {1} days, {2}:{3}, {4} users" -f $date, $uptime.days, $uptime.hours, $uptime.minutes, $usercount) 9 | } 10 | 11 | #usage 12 | #Get-Uptime -Computername pc001 13 | -------------------------------------------------------------------------------- /Invoke-ChatGPTQuestion.ps1: -------------------------------------------------------------------------------- 1 | Function Invoke-ChatGPTQuestion { 2 | [CmdletBinding()] 3 | param ( 4 | [string]$Question, 5 | [int]$MaxTokens = 500, 6 | [int]$Temperature = 0, 7 | [string]$Model = "text-davinci-003", 8 | [string]$APIKey 9 | ) 10 | # Set up the request body 11 | $body = @{ 12 | model = $Model 13 | prompt = $Question 14 | max_tokens = $MaxTokens 15 | temperature = $Temperature 16 | 17 | } | ConvertTo-Json 18 | 19 | $splat = @{ 20 | Method = 'Post' 21 | Uri = 'https://api.openai.com/v1/completions' 22 | Body = $body 23 | ContentType = 'application/json' 24 | Headers = @{'Authorization' = "Bearer $api_key" } 25 | } 26 | # Make the API call 27 | $response = Invoke-RestMethod @splat 28 | 29 | # Process the response 30 | $response.choices.text 31 | } 32 | #Invoke-ChatGPTQuestion -Question "who owns the knicks" -APIKey $api_key 33 | -------------------------------------------------------------------------------- /LocalGroupRights.psm1: -------------------------------------------------------------------------------- 1 | #Joe Rodriguez 2 | #joerod@gmail.com 3 | #version 1.0 4 | 5 | Function Get-LocalGroupRights { 6 | Param ( 7 | [Parameter(Mandatory = $true,Position=0)][string] $ComputerName, 8 | [Parameter(Position=1)][string] $Group = 'Administrators' 9 | 10 | ) 11 | $GroupInfo = [ADSI] "WinNT://$ComputerName/$Group,group" 12 | $Members = $GroupInfo.psbase.Invoke("Members") 13 | $Members | %{ $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } 14 | } 15 | 16 | #Get-LocalGroupRights -ComputerName Computer001 17 | 18 | Function Add-LocalGroupRights { 19 | Param ( 20 | [Parameter(Mandatory = $true,Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string] $ComputerName, 21 | [Parameter(Mandatory = $true,Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string] $Name, 22 | [Parameter(Mandatory = $true, Position = 2)][ValidateSet("User", "Group")] $Type, 23 | [Parameter(Position = 3)] $Group = 'Administrators' 24 | ) 25 | $GroupInfo = [ADSI] "WinNT://$ComputerName/$Group,group" 26 | $ToAdd = [ADSI] "WinNT://AD.JOEROD.COM/$Name,$Type" 27 | $GroupInfo.Add($ToAdd.Path) 28 | } 29 | 30 | #Add-LocalGroupRights -ComputerName Computer001 -Name joerod -Type User 31 | 32 | Function Remove-LocalGroupRights { 33 | Param ( 34 | [Parameter(Mandatory = $true,Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string] $ComputerName, 35 | [Parameter(Mandatory = $true,Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string] $Name, 36 | [Parameter(Mandatory = $true, Position = 2)][ValidateSet("User", "Group")] $Type, 37 | [Parameter(Position = 3)] $Group = 'Administrators' 38 | ) 39 | $GroupInfo = [ADSI] "WinNT://$ComputerName/$Group,group" 40 | $ToRemove = [ADSI] "WinNT://AD.JOEROD.COM/$Name,$Type" 41 | $GroupInfo.Remove($ToRemove.Path) 42 | } 43 | 44 | #Remove-LocalGroupRights -ComputerName Computer001 -Name joerod -Type User 45 | -------------------------------------------------------------------------------- /Microsoft.PowerShell_profile.ps1: -------------------------------------------------------------------------------- 1 | if($PSVersionTable.PSEdition -eq "Core"){ 2 | Install-Module WindowsCompatibility -Scope CurrentUser 3 | Import-WinModule Microsoft.PowerShell.Management 4 | } 5 | 6 | Install-Module -Name posh-git -Scope CurrentUser 7 | 8 | function prompt { 9 | $userinfo = (($env:USERNAME).tolower() + "@" + ($env:COMPUTERNAME).tolower()) 10 | $date = Get-Date -Format u 11 | $prompt = Write-Prompt ("PS {0}.{1}" -f $PSVersionTable.PSVersion.Major,$PSVersionTable.PSVersion.Minor) 12 | $prompt += Write-Prompt " $userinfo | " -ForegroundColor Green 13 | $prompt += & $GitPromptScriptBlock 14 | $prompt += Write-Prompt " | $date "-ForegroundColor Magenta 15 | if ($prompt) {$prompt} else {" "} 16 | } 17 | -------------------------------------------------------------------------------- /Mirror_AD_Groups.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Copies AD security groups from one user to another 4 | 5 | #> 6 | 7 | #Added a Param to make it easier to run this script use -CopyUser and -ToUser 8 | 9 | Function Copy-AdGroups{ 10 | 11 | Param ( 12 | [String] $CopyUser, 13 | [String] $ToUser 14 | ) 15 | 16 | Foraach ($GroupMember in((get-aduser $CopyUser -Properties memberOF).memberOF){ 17 | Add-ADPrincipalGroupMembership -Identity $ToUser -MemberOf $GroupMember 18 | Write-Verbose ("Copied {0} to {1}" -f $GroupMember, $ToUser) 19 | } 20 | 21 | } 22 | #Usage 23 | Copy-AdGroups-CopyUser joerod -ToUser avarod 24 | -------------------------------------------------------------------------------- /PS_GUI_AD_Real_Name_Finder.ps1: -------------------------------------------------------------------------------- 1 | #Wrote this as my first attempt at GUI POSH. This script accepts an Active Directory Users by SamAccontName and returns 2 | #a users Real Name as listed in AD. The end result is a pop-up window with the users real name. 3 | 4 | Function Get-RealName($SAMAccountName){ 5 | try { 6 | (Get-ADUser $SAMAccountName -ErrorAction Stop).Name 7 | } 8 | catch { 9 | Write-Output "Cannot find $SAMAccountName" 10 | } 11 | } 12 | 13 | Add-Type -AssemblyName System.Windows.Forms 14 | 15 | $GetActiveDirectoryUser = New-Object system.Windows.Forms.Form 16 | $GetActiveDirectoryUser.Text = "GetActiveDirectoryUser" 17 | $GetActiveDirectoryUser.TopMost = $true 18 | $GetActiveDirectoryUser.Width = 450 19 | $GetActiveDirectoryUser.Height = 150 20 | $GetActiveDirectoryUser.Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe") 21 | 22 | 23 | $textBox1_SAMAccountName = New-Object system.windows.Forms.TextBox 24 | $textBox1_SAMAccountName.Width = 165 25 | $textBox1_SAMAccountName.Height = 20 26 | $textBox1_SAMAccountName.location = new-object system.drawing.point(137, 26) 27 | $textBox1_SAMAccountName.Font = "Microsoft Sans Serif,10" 28 | $GetActiveDirectoryUser.controls.Add($textBox1_SAMAccountName) 29 | 30 | 31 | $button1_SAMAccountName = New-Object System.Windows.Forms.Button 32 | $button1_SAMAccountName.Text = "Real Name" 33 | $button1_SAMAccountName.Width = 100 34 | $button1_SAMAccountName.Height = 30 35 | $button1_SAMAccountName.Add_Click({ 36 | $wshell = New-Object -ComObject Wscript.Shell 37 | $wshell.Popup((Get-RealName -SamAccountName $textBox1_SAMAccountName.text), 0, "Real Name", 0x0) 38 | }) 39 | $button1_SAMAccountName.location = new-object system.drawing.point(314, 23) 40 | $button1_SAMAccountName.Font = "Microsoft Sans Serif,10" 41 | $GetActiveDirectoryUser.controls.Add($button1_SAMAccountName) 42 | 43 | 44 | $label1_SAMAccountName = New-Object system.windows.Forms.Label 45 | $label1_SAMAccountName.Text = "SAMAccountName" 46 | $label1_SAMAccountName.AutoSize = $true 47 | $label1_SAMAccountName.Width = 25 48 | $label1_SAMAccountName.Height = 10 49 | $label1_SAMAccountName.location = new-object system.drawing.point(13, 27) 50 | $label1_SAMAccountName.Font = "Microsoft Sans Serif,10" 51 | $GetActiveDirectoryUser.controls.Add($label1_SAMAccountName) 52 | 53 | 54 | [void] $GetActiveDirectoryUser.ShowDialog() 55 | $GetActiveDirectoryUser.Dispose() 56 | -------------------------------------------------------------------------------- /PoshWunderlist.psm1: -------------------------------------------------------------------------------- 1 | #You must specify an Access Token and Client ID for this script to work. Get this here https://developer.wunderlist.com/apps/new 2 | Function Get-WunderlistCredential { 3 | Param ( 4 | [string] $AccessToken, 5 | [string] $ClientID 6 | ) 7 | 8 | $auth = @{} 9 | $auth.Add("X-Access-Token", "$AccessToken") 10 | $auth.Add("X-Client-ID", "$ClientID") 11 | return $auth 12 | } 13 | 14 | $headers = Get-WunderlistCredential -AccessToken xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -ClientID xxxxxxxxxxxxxxxxxxxx 15 | 16 | 17 | #get list of all lists 18 | Function Get-Wunderlist{ 19 | Invoke-RestMethod -Uri "https://a.wunderlist.com/api/v1/lists" -Method Get -Headers $headers -ContentType 'application/json' 20 | } 21 | 22 | #Get-Wunderlist 23 | 24 | #Finds a Wunderlist with a title like $Title, min 3 characters max 30 25 | Function Find-Wunderlist{ 26 | Param ( 27 | [ValidateLength(3, 30)] 28 | [string] $Title 29 | ) 30 | foreach($list in (Get-Wunderlist)){ 31 | if ($list.title -like "*$Title*"){ 32 | $list 33 | } 34 | } 35 | } 36 | #Find-Wunderlist -Title Groceries 37 | 38 | #create a list 39 | Function Make-Wunderlist{ 40 | Param ( 41 | [string] $Title 42 | ) 43 | 44 | $body = @{ 45 | "title" = $Title 46 | } 47 | Invoke-RestMethod -Uri "https://a.wunderlist.com/api/v1/lists" -Method Post -Headers $headers -Body (ConvertTo-Json $body) -ContentType 'application/json' 48 | } 49 | 50 | #Make-Wunderlist -Title "Groceries" 51 | 52 | Function Remove-Wunderlist{ 53 | Param ( 54 | [int[]] $ListD, 55 | [string] $Revision 56 | ) 57 | 58 | Invoke-RestMethod -Uri ("https://a.wunderlist.com/api/v1/lists/$ListID" + "?revision=$Revision") -Method Delete -Headers $headers 59 | 60 | } 61 | 62 | #get all tasks in list 63 | Function Get-AllWunderlistTask{ 64 | Param ( 65 | [int] $TaskID, 66 | [string] $ShowCompleted = $false 67 | ) 68 | 69 | Invoke-RestMethod -Uri "https://a.wunderlist.com/api/v1/tasks?list_id=$TaskID&completed=$ShowCompleted" -Method Get -Headers $headers -ContentType 'application/json' 70 | 71 | } 72 | #Get-WunderlistTask -ListID 288253803 73 | #Get-WunderlistTask -ListID (Find-Wunderlist -Title Groceries).id 74 | 75 | #Create a task 76 | Function Add-WunderlistTask{ 77 | 78 | Param ( 79 | [int] $TaskID, 80 | [String] $TaskName 81 | ) 82 | 83 | $body = @{ 84 | list_id = $TaskID 85 | title = $TaskName 86 | } 87 | 88 | Invoke-RestMethod -Uri "https://a.wunderlist.com/api/v1/tasks" -Method Post -Headers $headers -Body (ConvertTo-Json $body) -ContentType 'application/json' 89 | } 90 | 91 | #Add-WunderlistTask -ListID 251331943 -TaskName "Function test" 92 | 93 | 94 | #Updates a task 95 | Function Update-WunderlistTask { 96 | Param ( 97 | [Parameter(Mandatory = $true)]$TaskID, 98 | [Parameter(Mandatory = $true)][int] $Revision, 99 | [int]$ListID, 100 | [string]$Title, 101 | [int]$AssigneeID, 102 | [bool]$Completed, 103 | [string]$RecurrenceType, 104 | [int]$RecurrenceCount, 105 | [string]$DueDate, 106 | [bool]$Starred, 107 | [array]$Remove 108 | ) 109 | #creats JSON body. Only adds parameters that are used. 110 | $body = @{} 111 | $body.add("revision",$Revision) 112 | if($ListID){$body.add("list_id",$ListID)} 113 | if($Title){$body.add("title",$Title)} 114 | if($AssigneeID){$body.add("assignee_id",$AssigneeID)} 115 | if($Completed){$body.add("completed",$Completed)} 116 | if($RecurrenceType){$body.add("recurrence_type",$RecurrenceType)} 117 | if($RecurrenceCount){$body.add("recurrence_count",$RecurrenceCount)} 118 | if($DueDate){$body.add("due_date",$DueDate)} 119 | if($Starred){$body.add("starred",$Starred)} 120 | if($Remove){$body.add("remove",$Remove)} 121 | 122 | Invoke-RestMethod -Uri "a.wunderlist.com/api/v1/tasks/$TaskID" -Method Patch -Headers $headers -Body (ConvertTo-Json $body) -ContentType 'application/json' 123 | } 124 | 125 | #Update-WunderlistTask -TaskID 2485757789 -Completed:$true -Revision 3 126 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | powershell 2 | ========== 3 | 4 | Powershell Scripts 5 | 6 | A bunch of powershell scripts that I've put together to help me with various admin tasks. 7 | 8 | This repo is a bit stale, I get paid for this stuff now-a-days so I commit to my company github a whole lot more. I come here to look at my old code and make it better. Unless I have a free weekend and a good idea :wink: 9 | 10 | Please submit merge requests to fix this 😊 11 | -------------------------------------------------------------------------------- /Remove-ItemByDate.ps1: -------------------------------------------------------------------------------- 1 | Function Remove-ItemByDate { 2 | <# 3 | .SYNOPSIS 4 | Removes a file or folder older than a specified date 5 | .DESCRIPTION 6 | Takes any strings for the file name or extension. 7 | .PARAMETER Item 8 | The file or folder to be compared to 9 | .PARAMETER Date 10 | The date the the file or folder must be younger than 11 | .EXAMPLE 12 | Remove-ItemByDate -Item D:\JoeRod\joerod\Desktop\movies -Date (Get-Date).AddMonths(-2) 13 | #> 14 | [CmdletBinding(SupportsShouldProcess=$True)] 15 | param( 16 | [string]$Item, 17 | [datetime]$Date 18 | ) 19 | 20 | $args = @{} 21 | 22 | if((Get-item $item).psiscontainer) { 23 | $args.Recurse = $true 24 | } 25 | else { 26 | $args.Recurse = $false 27 | } 28 | 29 | 30 | foreach($item_object in (Get-ChildItem $Item @args)){ 31 | if($item_object.CreationTime -lt $Date){ 32 | If ($PSCmdlet.ShouldProcess("Removing $($item_object.FullName)")) { 33 | Remove-item -LiteralPath $($item_object.FullName) -Force -Confirm:$false @args 34 | Write-Verbose "Removed $($item_object.FullName)" 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Remove-qBtorrent.ps1: -------------------------------------------------------------------------------- 1 | Function Remove-qBtorrent { 2 | #start session 3 | [CmdletBinding(SupportsShouldProcess = $True)] 4 | Param ($Password, 5 | $Username = 'admin', 6 | $Port = '6969' 7 | ) 8 | Begin { 9 | Write-Verbose "Creating Session" 10 | #get all torrents running 11 | [void](Invoke-RestMethod -Uri "http://localhost:$Port/login" -Body "username=admin&password=$Password" -Method Post -SessionVariable myWebSession) 12 | } 13 | Process { 14 | foreach ($torrent in (Invoke-RestMethod -Uri "http://localhost:$Port/query/torrents" -Method Get -WebSession $myWebSession)) { 15 | Write-Verbose ("Checking: {0} - {1}" -f $($torrent.name), $($torrent.progress).tostring("P")) 16 | if ($torrent.progress -eq 1) { 17 | #if torrent is completely downloaded delete it 18 | if ($PSCmdlet.ShouldProcess("Remove $($torrent.name)")) { 19 | Write-Verbose "Removing $($torrent.name)" 20 | Invoke-RestMethod -Uri "http://localhost:$Port/command/delete" -Method Post -WebSession $myWebSession -Body "hashes=$($torrent.hash)" 21 | } 22 | } 23 | } 24 | } 25 | } 26 | Remove-qBtorrent -Password "foobar" -Verbose 27 | -------------------------------------------------------------------------------- /Set-RedditWallPaper.ps1: -------------------------------------------------------------------------------- 1 | Function Set-RedditWallPaper { 2 | [CmdletBinding()] 3 | Param 4 | ( 5 | [parameter(Mandatory, 6 | ValueFromPipeline, Position = 0)] 7 | [String[]] 8 | $Subreddit, 9 | [parameter(ValueFromPipeline, Position = 1)] 10 | [String] 11 | $ImageLocation = [environment]::getfolderpath("mypictures"), 12 | [parameter(ValueFromPipeline, Position = 2)] 13 | [String] 14 | $ImageName = 'picture_of_the_day.jpg', 15 | [parameter(Mandatory, Position = 3)] 16 | [String] 17 | $TokenLocation 18 | ) 19 | 20 | Function Set-WallPaper($Value){ 21 | $setwallpapersrc = @" 22 | using System.Runtime.InteropServices; 23 | public class wallpaper 24 | { 25 | public const int SetDesktopWallpaper = 20; 26 | public const int UpdateIniFile = 0x01; 27 | public const int SendWinIniChange = 0x02; 28 | [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] 29 | private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni); 30 | public static void SetWallpaper ( string path ) 31 | { 32 | SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange ); 33 | } 34 | } 35 | "@ 36 | Add-Type -TypeDefinition $setwallpapersrc 37 | [wallpaper]::SetWallpaper($Value) 38 | } 39 | #ensure PSRAW module is installed 40 | if(-not (Get-Module PSRAW)){ 41 | Install-Module PSRAW 42 | } 43 | else { 44 | Import-Module PSRAW 45 | } 46 | #Import your PSRAW xml token file 47 | Import-RedditOAuthToken $TokenLocation 48 | Foreach($reddit in $Subreddit){ 49 | #randomly select an image from the subreddit top 50 | Write-Verbose "Retriving top scoring images from Subreddit" 51 | $result = Get-Random -InputObject ((Invoke-RedditRequest -uri $reddit).Response | ConvertFrom-Json).data.children.data 52 | #pulls the image data 53 | Write-Verbose "Finding jpg images" 54 | [string]$picurl = $result.url | Select-String -Pattern "jpg" 55 | $output = (Join-Path -Path $ImageLocation -ChildPath $ImageName ) 56 | #saves image locally 57 | Invoke-RestMethod -uri $picurl.Trim() -OutFile $output 58 | Write-Verbose "Changing desktop image to: $($result.title)" 59 | #sets wallpaper 60 | Set-WallPaper -value $output 61 | } 62 | } 63 | 64 | #Set-RedditWallPaper -Subreddit "https://oauth.reddit.com/r/EarthPorn/top" -TokenLocation "C:\Users\joerod\Documents\psrawtoken.xml" -ImageLocation "C:\Users\joerod\Pictures" -Verbose 65 | -------------------------------------------------------------------------------- /ad_unix_attributes.ps1: -------------------------------------------------------------------------------- 1 | #sets unix attribues and creates a group based on the last attribute avalible 2 | 3 | Param( 4 | [Parameter(Position=0,mandatory=$true)] 5 | [string]$Username 6 | ) 7 | Function Check-account{ 8 | get-aduser -Identity $Username 9 | } 10 | 11 | Function Check-GID{ 12 | $user = ("g_" + "$username") 13 | get-adgroup -SearchBase "OU=UnixGroups,DC=Contoso,DC=LOCAL" -filter 'Name -eq $user' 14 | } 15 | 16 | Function NextGid { 17 | #gets the next avalible gid number to assign to the object 18 | $next = ((Get-ADObject -SearchBase "OU=UnixGroups,DC=Contoso,DC=LOCAL" -filter {gidnumber -like "*"} -Properties gidnumber).gidnumber | sort gidnumber)[-1] 19 | 20 | #skips GID 8000 21 | if ($next -eq 8000){ 22 | $next = 8001 23 | $next 24 | } 25 | else{ 26 | $next++ 27 | $next 28 | } 29 | } 30 | $nextid = NextGid 31 | 32 | Function Create-Group{ 33 | $group_name = ("g_" + "$username") 34 | #creates group 35 | New-ADGroup -Path "OU=UnixGroups,DC=Contoso,DC=LOCAL" -Name $group_name -GroupScope Global 36 | 37 | #adds unix attributes to newly created group 38 | Set-ADGroup -Identity $group_name -Add @{"gidNumber" = "$nextid"} 39 | Set-ADGroup -Identity $group_name -Add @{"msSFU30NisDomain" = 'Contso'} 40 | } 41 | 42 | Function Check-user{ 43 | $check = get-aduser -Identity $Username -Properties * |select -ExpandProperty uidNumber 44 | if($check -ne $null){ 45 | Write-Output "$Username already has a UID #$check" 46 | } 47 | 48 | else { 49 | Set-ADUser -Identity $Username -replace @{msSFU30NisDomain = 'contoso'} 50 | Set-ADUser -Identity $Username -replace @{loginshell = '/bin/bash'} 51 | Set-ADUser -Identity $Username -replace @{gidnumber = "$nextid"} 52 | Set-ADUser -Identity $Username -replace @{uidnumber = "$nextid"} 53 | 54 | Write-Output "Unix attributes added to $username" 55 | } 56 | } 57 | 58 | $check = Check-GID 59 | $check_account = Check-account 60 | 61 | if(($check -eq $null) -and ($check_account -ne $null)){ 62 | NextGid 63 | Create-Group 64 | Check-user 65 | Write-Output "Created Group and updated $username Unix attributes" 66 | } 67 | 68 | else { 69 | if ($check_account -ne $null){ 70 | Check-account 71 | Check-user 72 | } 73 | } 74 | 75 | 76 | -------------------------------------------------------------------------------- /apostrophes.ps1: -------------------------------------------------------------------------------- 1 | #i'll use this script in future scripts when using the get-aduser cmdlet. I had problems when a user has an apostrophes 2 | #in their name 3 | 4 | $Name = "Jermaine O'Neal" 5 | if($Name.contains("'")){($Name.replace( "'","''"))} 6 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # Starter pipeline 2 | # Start with a minimal pipeline that you can customize to build and deploy your code. 3 | # Add steps that build, run tests, deploy, and more: 4 | # https://aka.ms/yaml 5 | 6 | trigger: 7 | - master 8 | 9 | pool: 10 | vmImage: 'windows-latest' 11 | 12 | steps: 13 | - pwsh: | 14 | Get-Date 15 | #workingDirectory: # 16 | displayName: "Test" 17 | #env: # mapping of environment variables to add 18 | - task: PowerShell Script Analyzer@1 19 | inputs: 20 | PsFolder: '$(currentDirectory)' 21 | FailOnError: true -------------------------------------------------------------------------------- /bing_rewards.ps1: -------------------------------------------------------------------------------- 1 | #I created this script to gain more Bing Rewards. I have it running as a schedualed task every hour while I'm asleep. 2 | #The script gets its searches by querying google trends for that day then it opens IE with the search. 3 | Add-Type -AssemblyName System.Web 4 | 5 | Function QueryBing{ 6 | [cmdletbinding()] 7 | param ( 8 | [parameter(mandatory = $true, ValueFromPipeline = $True, Position = 0)] 9 | [string[]] $Query) 10 | $IE = New-Object -ComObject internetexplorer.application 11 | $Query = [System.Web.HttpUtility]::UrlEncode($Query) 12 | $IE.navigate2("https://www.bing.com/search?q=" + $query) 13 | $IE.visible = $true 14 | Start-Sleep -Seconds 2 15 | Get-Process iexplore | Stop-Process -Force 16 | #add query to form from bing API 17 | } 18 | 19 | Function Get-GoogleTrends{ 20 | [xml] $result = Invoke-WebRequest http://www.google.com/trends/hottrends/atom/feed?pn=p1 21 | $result.rss.channel.item.title 22 | } 23 | 24 | #loop twice because the xml from google only yeilds 20 results and bing allows 30 queries for rewards 25 | $i = 0 26 | for ($i -eq 0; $i -lt 2;) 27 | { 28 | Get-GoogleTrends | % { QueryBing $_ } 29 | $i++ 30 | } 31 | -------------------------------------------------------------------------------- /bulk_password.ps1: -------------------------------------------------------------------------------- 1 | #used for output trascript 2 | $ErrorActionPreference="SilentlyContinue" 3 | Stop-Transcript | out-null 4 | $ErrorActionPreference = "Continue" 5 | 6 | #set this to the location of the gam binaries 7 | Set-Alias gam C:\gam\gam.exe 8 | Start-Transcript -path C:\scripts\password_output.txt -append 9 | #Imports data from csv, mandatory column 1 (email) address 10 | foreach($column in (Import-Csv C:\scripts\users.csv)) 11 | { 12 | $pass = $null 13 | #creates random 8 charecter password 14 | $r = New-Object System.Random 15 | 1..8 | % { $pass += [char]$r.next(33,126) } 16 | 17 | gam update user $($column.email) password $pass 18 | gam update user $($column.email) suspended on 19 | 20 | Write-Host "$($column.email) password changed - $pass - Suspended `r" 21 | 22 | } 23 | 24 | Stop-Transcript 25 | -------------------------------------------------------------------------------- /change_sip_ocs.ps1: -------------------------------------------------------------------------------- 1 | 2 | #splat this 3 | #This scrip will change the OCS (Outlook Communicator) login to conform with the users AD login. 4 | 5 | 6 | ForEach ($user in (Get-ADUser -filter { ObjectClass -eq "user" } -SearchBase 'ou=users,dc=contoso,dc=local' -SearchScope Subtree -Properties *|Select-Object SamAccountName, Name)) { 7 | 8 | Write-Host "Adding SIP" $user.samaccountname "to" $user.name 9 | Set-ADUser -Identity $user.samaccountname -clear ProxyAddresses 10 | Set-ADUser -Identity $user.samaccountname -Add @{ProxyAddresses = 'sip:' + $user.samaccountname + '@im.contoso.com'} 11 | Set-ADUser -Identity $user.samaccountname -clear msRTCSIP-PrimaryUserAddress 12 | Set-ADUser -Identity $user.samaccountname -Add @{"msRTCSIP-PrimaryUserAddress" = 'sip:' + $user.samaccountname + '@im.contoso.com'} 13 | } 14 | -------------------------------------------------------------------------------- /check_suspended.ps1: -------------------------------------------------------------------------------- 1 | #set this to the location of the gam binaries 2 | Set-Alias gam C:\gam\gam.exe 3 | 4 | #Imports data from csv, mandatory column 1 (email) address 5 | 6 | foreach($i in (Import-Csv C:\scripts\users.csv){ 7 | 8 | $suspended = gam info user $($i.email) | Select-String -pattern "Account Suspended: false" 9 | 10 | if ($suspended -eq $null) { 11 | $($i.email) | Out-File -FilePath C:\scripts\not_suspended.txt -append -Encoding utf8 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /copy_security_groups.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [Parameter(Position=0,mandatory=$true)] 3 | [string]$SourceGroup, 4 | 5 | [Parameter(Position=0,mandatory=$true)] 6 | [string]$DestinationGroup 7 | ) 8 | 9 | try{ 10 | $SourceGroupCheck = Get-ADGroup -Identity $SourceGroup 11 | $DestinationGroupCheck = Get-ADGroup -filter {sAMAccountName -eq $DestinationGroup} 12 | 13 | $Group = Get-ADGroupMember -Identity $SourceGroupCheck.SamAccountName 14 | 15 | if($DestinationGroupCheck){ 16 | Write-Output "Copying users from $SourceGroup to $DestinationGroup" 17 | foreach ($Person in $Group) { 18 | Add-ADGroupMember -Identity $DestinationGroupCheck.SamAccountName -Members $Person.distinguishedname 19 | 20 | } 21 | } 22 | 23 | else { 24 | Write-Output "$DestinationGroup does not exist... Creating Group" 25 | New-ADGroup -Name $DestinationGroup -Path ($SourceGroupCheck.DistinguishedName -replace '^[^,]*,','') -GroupScope Global 26 | foreach ($Person in $Group) { 27 | Add-ADGroupMember -Identity $DestinationGroup -Members $Person 28 | 29 | } 30 | Write-Output "$DestinationGroup group created and users copied" 31 | } 32 | 33 | } 34 | catch{ 35 | $error[0] 36 | } 37 | -------------------------------------------------------------------------------- /create_admin_account.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Created this script copy make admin accounts for best practices. It copies the security groups and creates a new AD 4 | Account named admin 5 | 6 | .EXAMPLE 7 | create_admin_account.ps1 -user someuser 8 | 9 | #> 10 | 11 | Param( 12 | [Parameter(mandatory)] 13 | [string]$User 14 | ) 15 | 16 | function Get-GroupMember($User) { 17 | #gets groups that are not distribution groups 18 | foreach ($group in ((Get-ADUser -Identity $user -Properties memberof).memberof)) { 19 | if ($group.GroupType -match "SecurityEnabled") { 20 | return $group 21 | } 22 | } 23 | } 24 | 25 | function Set-NewUser($User) { 26 | #creates new user 27 | $newuser = ($user.substring(0, 4) + "admin" ) 28 | $oldaccount = Get-ADUser -Identity $user -Properties * 29 | #Write-Output "User account created... $newuser" 30 | 31 | #parses out OU path to set to new users OU 32 | $LikeUN = $oldaccount.DistinguishedName | Out-String 33 | $OU = $LikeUN.Substring($LikeUN.IndexOf("OU=")) 34 | #Write-Output "User will be located in $OU" 35 | 36 | #sets password 37 | $password = "Strong Password" | ConvertTo-SecureString -AsPlainText -Force 38 | New-ADUser -Name ($($oldaccount).displayname + " (Admin)") -SamAccountName $newuser -AccountPassword $password -UserPrincipalName ($newuser + "@CONTOSO.LOCAL") -GivenName $($oldaccount).givenname -Surname $($oldaccount).Surname ` 39 | -DisplayName ($($oldaccount).displayname + " (Admin)") -Path $OU -ChangePasswordAtLogon $true -Enabled $true 40 | $newuser 41 | 42 | #sets email address for new admin account to admins primary account 43 | Set-ADUser -Identity $newuser -add @{mail = (Get-ADUser -Identity $user -Properties mail).mail } 44 | Set-ADUser -Identity $newuser -EmailAddress (Get-ADUser -Identity $user -Properties mail).mail 45 | } 46 | 47 | function Add-Groups { 48 | foreach ($addgroup in $groupmember.samaccountname) { 49 | Write-Output "added to $addgroup" 50 | Add-ADGroupMember $addgroup -Members $brandnewuser 51 | } 52 | } 53 | 54 | Get-GroupMember 55 | Set-Newuser 56 | Start-Sleep -Sleep 5 57 | Write-Output "Waiting for AD to catch up with the script" 58 | Add-Groups 59 | -------------------------------------------------------------------------------- /delete_user_folders.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | This script will find user folders in C:\Users and delete them. I've added some logic to omit folders that should not be deleted. 4 | WinRM is used to connect to each box and run a cmd command 5 | 6 | .EXAMPLE 7 | delete_user_folders.ps1 8 | 9 | #> 10 | 11 | 12 | $computers = GC C:\users\joerod\Desktop\list.txt 13 | 14 | foreach ($computer in $computers){ 15 | 16 | Invoke-Command -ComputerName $computer { 17 | $folders = Get-ChildItem C:\Users |select -expand name 18 | foreach ($folder in $folders){ 19 | if(($folder -notlike "Public") -and ($folder -notlike "administrator") -and ($folder -notlike "Default*")){ 20 | Write-Output "removing $folder" 21 | cmd.exe /c del "c:\Users\$folder" /f/s/q/a 22 | cmd.exe /c rmdir "c:\Users\$folder" /s/q} 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dns_a_records.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [string]$DNSServer, 3 | [string]$DomainName, 4 | [string]$IPAddress 5 | ) 6 | 7 | get-wmiobject -ComputerName $DNSServer -Namespace root\microsoftDNS -Class MicrosoftDNS_ResourceRecord -Filter "domainname='$DomainName'"| 8 | select IPAddress, Ownername | 9 | ? {$_.ipaddress -like '$IPAddress'} | 10 | sort ownername 11 | -------------------------------------------------------------------------------- /empty_ou.ps1: -------------------------------------------------------------------------------- 1 | #This script finds empty sub OUs in the OU listed in the 4th line and removes them 2 | 3 | function Get-EmptyOU{ 4 | Get-ADOrganizationalUnit -Filter * -SearchBase "OU=Empty,DC=contoso, DC=local" | 5 | Where-Object {-not ( Get-ADObject -Filter * -SearchBase $_.Distinguishedname -SearchScope OneLevel -ResultSetSize 1 )} | 6 | Select-Object -ExpandProperty Distinguishedname 7 | } 8 | 9 | #this removes each empty OU 10 | foreach($i in Get-EmptyOU){ 11 | 12 | #shows progress of script 13 | Write-Output "Removing $i" 14 | 15 | #removes accidental deletion of object 16 | Set-ADObject $i -ProtectedFromAccidentalDeletion $false 17 | 18 | #removes the object from AD 19 | Remove-ADOrganizationalUnit -Identity $i -confirm:$false 20 | 21 | } 22 | 23 | -------------------------------------------------------------------------------- /exchange_db_status.ps1: -------------------------------------------------------------------------------- 1 | add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 2 | 3 | #stylesheet for html email 4 | $style = "" 9 | 10 | 11 | Function Get-DBstatus{ 12 | foreach($server in (@("mailboxserver1","mailboxserver2","mailboxserver3"))){ 13 | Get-MailboxDatabaseCopyStatus -Server $server |Select DatabaseName, Mailboxserver,Status |? {($_.Status -ne "Healthy") -and ($_.Status -ne "Mounted") -and ($_.Status -notlike "Seeding*") } 14 | # Things to fix, ConvertTo-Html -Head $style 15 | } 16 | } 17 | if($status -ne 0){ 18 | Send-MailMessage -To joerod@contoso.com ` 19 | -from exchangedbalerts@contoso.com -Body (Get-DBstatus|Out-String) -subject "Error on Exchange DB" -smtpserver stmpmailbox -priority High 20 | } 21 | 22 | -------------------------------------------------------------------------------- /file_date_and_size.ps1: -------------------------------------------------------------------------------- 1 | <#this script will get a list of files in a folder and its subfolders. It will then look for files larger then 0kb and 2 | older then 10 minutes. 3 | #> 4 | 5 | 6 | $age = 10 7 | $array = @() 8 | $filter = 0 9 | $folder = 'C:\Stuff' 10 | 11 | foreach($file in (Get-ChildItem $folder -Recurse | ? { ! $_.PSIsContainer })){ 12 | if((Get-Item $file.FullName).length -gt 0kb){ 13 | $elapsedtime = New-TimeSpan -Start $file.LastWriteTime -End (get-date) 14 | if([System.Math]::Round($elapsedtime.TotalMinutes,0) -ge $age ){ 15 | $fileage = [System.Math]::Round($elapsedtime.TotalMinutes,0) 16 | $shortname = ($file.FullName).replace("$folder","") 17 | $array += "$shortname, Age: $fileage Min |" 18 | $filter = 1 19 | } 20 | } 21 | } 22 | if($filter -eq 1){ 23 | Write-Output "Statistic: 3" 24 | Write-Output "Message: Unprocessed file: $array" 25 | } 26 | else { 27 | Write-Output "Statistic: 0" 28 | Write-Output "Message: OK - No unprocessed files found" 29 | } 30 | -------------------------------------------------------------------------------- /file_migration.ps1: -------------------------------------------------------------------------------- 1 | <# Prerequisite robocopy 2 | RSAT 3 | 4 | This script will copy files from one server (server_a) to another (server_b) using robocopy and a list of folders. Populate a list of SAMAccount Names into a file named 5 | userlist.txt. 6 | First we check to see if the folder being copied to the destination server (server_b) exists on the host server (server_a), 7 | if not the folder is created and the ACL are modified, Then the users AD profile is updated with the new home drive and specified drive letter. 8 | 9 | If the folder already exists on server_a robocopy copies all the contents including file perms and sends a log everything 10 | #> 11 | 12 | foreach ($user in (Get-Content C:\Users\admin\Desktop\userlist.txt)) { 13 | 14 | #checks if user has a home directory if not it creates one on target server 15 | if ((Test-Path -Path "\\server_a\d$\user\$user") -eq $false) { 16 | #creates new path since one does not exist 17 | $CreatePath = New-Item -Path "\\server_b\f$\UsersNY\$user" -itemtype directory 18 | $CreatePath = "\\server_b\f$\UserNew\$user" 19 | 20 | #sets file permsion on new folder 21 | $acl = Get-Acl $CreatePath 22 | $permission = "contoso\$user", "Modify", "ContainerInherit, ObjectInherit", "None", "Allow" 23 | $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission 24 | $acl.SetAccessRule($accessRule) 25 | $acl | Set-Acl $CreatePath 26 | 27 | #adds new home directory to AD 28 | $drive = "\\server_b\f$\UsersNew\" 29 | Set-ADUser $user -HomeDirectory ("$drive" + "$user") -HomeDrive U 30 | 31 | } 32 | else { 33 | #Copies data (only delta if file already exist) 34 | Send-mailmessage -to "Joe Rodriguez " -From "Joe Rodriguez " -Subject "Started Copying $User" -SmtpServer "mailserver.company.com" 35 | robocopy \\server_a\f$\UsersOld\$user \\server_b\f$\UsersNew\$user /e /COPYALL /xo /Z /R:1000000 /W:1 /LOG+:C:\robocopy.log /tee 36 | #Sets home drive in AD 37 | $drive = "\\contoso\dfs\UsersNew\" 38 | Set-ADUser $user -HomeDirectory ("$drive" + "$user") -HomeDrive U 39 | Send-mailmessage -to "Joe Rodriguez "" -From "Joe Rodriguez "" -Subject "$User has been moved" -SmtpServer "mailserver.company.com" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /find_local_admins.ps1: -------------------------------------------------------------------------------- 1 | #this script will find all machines in an OU then show who is in the local administrators group. 2 | 3 | Function Get-Complist{ 4 | Get-ADObject -Filter { ObjectClass -eq "computer" } -SearchBase "OU=Workstations,DC=Contoso,DC=LOCAL"| 5 | Select-Object -expandproperty Name |Sort 6 | } 7 | 8 | 9 | Function find_local_admin{ 10 | foreach($i in Get-Complist){ 11 | #test if machine is on the network 12 | if (!(Test-Connection -computername $i -count 1 -Quiet -ErrorAction SilentlyContinue)) { 13 | Write-Warning "$i is Unavailable (Not Pingable)" | tee-object -filepath c:\ 14 | Continue 15 | } 16 | try{ 17 | invoke-command { 18 | 19 | $members = net localgroup administrators |?{$_ -AND $_ -notmatch "command completed successfully"} | select -skip 4 20 | $Results = @() 21 | ForEach($member in $members){ 22 | New-Object PSObject -Property @{ 23 | Computername = $env:COMPUTERNAME 24 | Users=$member 25 | } 26 | } 27 | } -computer $i -HideComputerName | Select * -ExcludeProperty RunspaceID 28 | } 29 | catch{ 30 | Write-Warning "$i - Cannot WinRM" 31 | } 32 | } 33 | } 34 | find_local_admin | select * -ExcludeProperty PSComputerName,PSShowComputerName |Export-Csv C:\Users\joerod\Desktop\admins.csv -NoTypeInformation -Append 35 | -------------------------------------------------------------------------------- /find_os.ps1: -------------------------------------------------------------------------------- 1 | 2 | #this script takes a list of computers either IP or Name and shows what OS they are running. 3 | function Find-OS { 4 | #Requires -Version 5.1 5 | Param( 6 | [array[]]$ComputerName = $env:COMPUTERNAME 7 | ) 8 | 9 | foreach($x in $ComputerName){ 10 | 11 | (Get-WmiObject Win32_OperatingSystem -computer $x).caption | foreach{ 12 | [PSCustomObject]@{ 13 | ComputerName = $x -join '' 14 | "OS Version" = $_.caption -join '' 15 | } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /find_user_groups.ps1: -------------------------------------------------------------------------------- 1 | #this will find all the users in the domain and what groups they belong to. Editing the Get-ADUser filter will narrow down 2 | # the results 3 | 4 | Function Export-usernamegroup{ 5 | 6 | foreach ($username in (Get-ADUser -filter * |select -expand samaccountname)) { 7 | 8 | Get-ADPrincipalGroupMembership $username | select -ExpandProperty name | 9 | % { 10 | 11 | New-Object -TypeName PSCustomObject -Property @{ 12 | Name = Get-ADUser -Identity $username -Properties Name | select -ExpandProperty Name 13 | Group = $_ 14 | 15 | } 16 | } 17 | 18 | } 19 | } 20 | 21 | Export-usernamegroup 22 | -------------------------------------------------------------------------------- /folder_permissions.ps1: -------------------------------------------------------------------------------- 1 | #This script will find a specified folder on a remote machine and give modify rights to "Authenticated Users" 2 | 3 | Invoke-Command -ComputerName machine { 4 | function find-path{ 5 | $folderName = "Outlook" 6 | Get-ChildItem -Recurse -Force "C:\Program Files (x86)" -ErrorAction SilentlyContinue | 7 | Where-Object { ($_.PSIsContainer -eq $true) -and ( $_.Name -like "*$folderName*") } | 8 | Select-Object -expand FullName 9 | } 10 | 11 | 12 | foreach($folder in find-path){ 13 | $acl = Get-Acl $folder 14 | $myGroup = "NT AUTHORITY\Authenticated Users" 15 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "Write", "ContainerInherit, ObjectInherit", "None", "Allow") 16 | $acl.AddAccessRule($rule) 17 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "Read", "ContainerInherit, ObjectInherit", "None", "Allow") 18 | $acl.AddAccessRule($rule) 19 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "ReadAndExecute", "ContainerInherit, ObjectInherit", "None", "Allow") 20 | $acl.AddAccessRule($rule) 21 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "ListDirectory", "ContainerInherit, ObjectInherit", "None", "Allow") 22 | $acl.AddAccessRule($rule) 23 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "Modify", "ContainerInherit, ObjectInherit", "None", "Allow") 24 | $acl.AddAccessRule($rule) 25 | Set-Acl $folder $acl 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /gce_vm.ps1: -------------------------------------------------------------------------------- 1 | # GCE spin up traditional vm 2 | $region = "us-east1" 3 | $zone = "us-east1-b" 4 | $DiskSizeGB = "50" 5 | $MemorySizeMB = "16384" 6 | 7 | Write-Output "Allocating public IP address..." 8 | $address = Add-GceAddress -Name $Name -Region $region 9 | Write-Output "Creating boot disk..." 10 | $bootDiskImage = Get-GceImage "windows-cloud" -Family "windows-2016" 11 | $bootDisk = New-GceDisk $Name -DiskType "pd-ssd" -Image $bootDiskImage -SizeGb $DiskSizeGB -Zone $zone 12 | Write-Output "Creating new Compute instance..." 13 | Add-GceInstance $Name -Address ($address).AddressValue -BootDisk $bootDisk -CustomCpu 2 -CustomMemory $MemorySizeMB -Zone $zone -Region $region 14 | 15 | #remove vm 16 | get-GceInstance testvm6 -Zone $zone| Remove-GceInstance 17 | -------------------------------------------------------------------------------- /home_zestimate.ps1: -------------------------------------------------------------------------------- 1 | #I wrote this script to programaticly find the 'Zestimate' of a property using the Zillow API 2 | #Usage Find-HousePrice -Address '123 Sesame St.' -Citystatezip 11237 3 | #You must register on the Zillow site for a ZWSID for this scirpt to work 4 | 5 | Function Find-HousePrice($Address, $CityStateZip){ 6 | [Reflection.Assembly]::LoadWithPartialName('system.web') | out-null 7 | $address = [System.Web.HttpUtility]::UrlEncode($address) 8 | $citystatezip = [System.Web.HttpUtility]::UrlEncode($citystatezip) 9 | 10 | $ZWSID = "" 11 | $result = Invoke-RestMethod ("http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=" + $ZWSID + "&address=$address&citystatezip=$citystatezip") -Method Get 12 | "{0:C0}" -f [int] $result.searchresults.response.results.result.zestimate.amount.'#text' 13 | } 14 | 15 | Find-HousePrice -Address '123 Sesame St' -CityStateZip 11211 16 | -------------------------------------------------------------------------------- /idrac_cim_job.ps1: -------------------------------------------------------------------------------- 1 | # reboot_type: 2 | # - 1 = PowerCycle, 2 = Graceful Reboot without forced shutdown, 3 = Graceful reboot with forced shutdown 3 | 4 | $properties = @{SystemCreationClassName="DCIM_ComputerSystem" 5 | CreationClassName="DCIM_JobService" 6 | SystemName="IDRAC:ID" 7 | Name="SoftwareUpdate" 8 | } 9 | $instance = New-CimInstance -ClassName DCIM_SoftwareInstallationService -Namespace root/dcim -ClientOnly -Key @($properties.keys) -Property $properties 10 | 11 | $Parameters = @{ 12 | RebootJobType = 2 13 | } 14 | 15 | Invoke-CimMethod -InputObject $instance -MethodName CreateRebootJob -CimSession $iDRACSession -Arguments $Parameters 16 | -------------------------------------------------------------------------------- /install_applications_wmi.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | I wrote this script to install a VCM client on a number of servers. We do not have winrm enabled on any of our servers so I 3 | used the Invoke-WmiMethod cmdlet to install the application. 4 | 5 | This script will copy the nessicary files to the destination server then install, it will also provide logs for installation and 6 | connection errors. 7 | #> 8 | 9 | $DriveLetter = 'c' 10 | $path = 'Software' 11 | $logpath = 'C:\Script_logs' 12 | 13 | #creates folder on local machine to save logs to 14 | if(-not (Test-Path $logpath -PathType Container)){ 15 | New-Item -Path $logpath -type directory -Force |Out-Null 16 | } 17 | 18 | #begin main script 19 | foreach ($computer in (gc C:\Users\joerod\Desktop\hostlist.txt)){ 20 | try{ 21 | if(Test-Path \\$Computer\$DriveLetter$\$path -ea Stop){ 22 | Write-Output "Trying to install application on $computer..." 23 | 24 | } 25 | 26 | else{ 27 | New-Item -Path \\$Computer\$DriveLetter$\$Path -type directory -Force -ea Stop |Out-Null 28 | } 29 | Write-output "Copying files" 30 | Copy-Item -Path C:\Users\joerod\Desktop\vcmagent\* -Destination \\$Computer\$DriveLetter$\$Path 31 | 32 | $args = "cmd /c c:\software\CMAgentInstall.exe /s INSTALLPATH=%Systemroot%\CMAgent PORT=26542 CERT=C:\Software\VMware_VCM_Enterprise_Certificate_E5BC8577-798A-4721-BB5A-357A45C4378A.pem" 33 | $result = Invoke-WmiMethod -ComputerName $computer -Class Win32_Process -Name Create -ArgumentList $args 34 | if ($result.ReturnValue -ne 0) 35 | { 36 | $exception = New-Object System.ComponentModel.Win32Exception([int]$result.ReturnValue) 37 | $msg_failinstall = "Error launching installer on computer ${computer}: $($exception.Message)" 38 | Write-Warning $msg_install 39 | $msg_failinstall |Out-File $logpath\application_install_$(get-date -f MM-dd-yyyy).log -Append 40 | 41 | } 42 | else { 43 | $msg_successinstall = "Application has installed successfully on $computer" 44 | Write-Output $msg_successinstall 45 | $msg_successinstall |Out-File $logpath\application_install_$(get-date -f MM-dd-yyyy).log -Append 46 | 47 | } 48 | 49 | } 50 | catch{ 51 | $msg_connect = "Can't connect to $computer" 52 | Write-Warning $msg_connect 53 | $msg_connect |Out-File $logpath\connection_install_$(get-date -f MM-dd-yyyy).log -Append 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /leech.ps1: -------------------------------------------------------------------------------- 1 | #Requires –Version 7 2 | <#PSScriptInfo 3 | 4 | .VERSION 1.0 5 | 6 | .AUTHOR joerod@gmail.com 7 | 8 | .TAGS qbittorrent 9 | 10 | .RELEASENOTES 11 | $computer = '192.168.1.4' 12 | .\leech.ps1 -Username "admin" -Password "password" -Token "7YBGs5ZtfV2bPW6ANFea" -Computer $computer -Plex $computer 13 | #> 14 | 15 | <# 16 | .DESCRIPTION 17 | if you're the kinda person who likes to leech torrents this ones for you. 18 | #> 19 | 20 | param( 21 | $Username = 'admin', # password for qbittorrent 22 | $Password, # API password for qbittorrent 23 | $Token, # Token for plex API 24 | $Computer, # where qbittorrent is running 25 | $Port = '6969', # port for qbittorrent 26 | $Plex, # address of plex server 27 | [int]$minutes = '1' # how often to check on downloading file(s) 28 | ) 29 | 30 | Function Connect-qBtorrent { 31 | [CmdletBinding()] 32 | #[OutputType([Microsoft.PowerShell.Commands.WebRequestSession])] 33 | Param ( 34 | $Username, 35 | $Password, 36 | $Computer, 37 | $Port 38 | ) 39 | Invoke-RestMethod -Uri "http://$($computer):$($Port)/api/v2/auth/login" -Body "username=$Username&password=$Password" -Method Post -SessionVariable webSession 40 | $Global:Session = $websession 41 | } 42 | Function Remove-qBtorrent { 43 | #start session 44 | [CmdletBinding(SupportsShouldProcess = $True)] 45 | Param ( 46 | $Hash, 47 | $DeleteFiles = 'false', 48 | $Computer, 49 | $Port, 50 | $WebSession 51 | ) 52 | #if torrent is completely downloaded delete it 53 | if ($PSCmdlet.ShouldProcess("Removing $Hash")) { 54 | Invoke-RestMethod -Uri "http://$($computer):$($Port)/api/v2/torrents/delete?hashes=$($Hash)&deleteFiles=$($DeleteFiles)" -Method Get -webSession $webSession 55 | } 56 | } 57 | Function Get-qBtorrentInfo { 58 | #start session 59 | [CmdletBinding()] 60 | Param ( 61 | $Filter, 62 | $WebSession, 63 | $Computer, 64 | $Port 65 | ) 66 | $uri = "http://$($computer):$($Port)/api/v2/torrents/info" 67 | if ($Filter) { 68 | $uri = $uri + "?filter=$($Filter)" 69 | } 70 | Invoke-RestMethod -Uri $uri -Method Get -webSession $webSession 71 | } 72 | 73 | Connect-qBtorrent -Username $Username -Password $Password -Computer $Computer -Port $Port 74 | while ($results = Get-qBtorrentInfo -WebSession $session -Computer $Computer -Port $port) { 75 | foreach ($result in $results) { 76 | switch ($result.state) { 77 | { $_ -in 'uploading', 'stalledUP' } { 78 | Write-output "Removing $($result.name)" 79 | Remove-qBtorrent -WebSession $session -Hash $result.hash -Computer $Computer -Port $port 80 | # refresh plex if a movie is downloaded 81 | if ($Plex) { 82 | $return = Invoke-restmethod -uri "http://$($Plex):32400/library/sections?X-Plex-Token=$($token)" 83 | foreach ($path in ($results.save_path | Select-Object -Unique)) { 84 | if ($id = $return.MediaContainer.Directory.Location | Where-Object { ($_.path + "\") -eq $path }) { 85 | Invoke-restmethod -uri "http://$($Plex):32400/library/sections/$($id.id)/refresh??force=1&X-Plex-Token=$($token)" 86 | } 87 | else { 88 | Write-warning ("Could not find folder {0} to refresh in Plex" -f ($($id.path) ? $($id.path) : "Null")) 89 | } 90 | } 91 | } 92 | } 93 | default { 94 | Write-Warning ("Still leeching: {0} - {1}%" -f $($result.name), [math]::Round($($($result.progress) * 100), 2)) 95 | } 96 | } 97 | if ((Get-qBtorrentInfo -WebSession $session -Computer $Computer -Port $port).Count -eq 0) { 98 | Write-output "You're all leeched up... Ending" 99 | return 100 | } 101 | } 102 | Start-Sleep ($minutes * 60) 103 | } 104 | -------------------------------------------------------------------------------- /local_admin_users.ps1: -------------------------------------------------------------------------------- 1 | #Gets list of machines from specified OU 2 | Function Get-CompList{ 3 | (Get-ADObject -Filter { ObjectClass -eq "computer" } -SearchBase "OU=Resources,DC=NWTraders,DC=LOCAL").Name |Sort 4 | } 5 | 6 | 7 | <# 8 | Gets a list of local Admin accounts from each computers in OU from Get-Complist function, will ping machine 9 | to see if its alive and write error message if machine is unavalible 10 | #> 11 | Function Get-AdminGroups{ 12 | 13 | foreach($i in Get-CompList){ 14 | if (!(Test-Connection -computername $i -count 1 -Quiet -ErrorAction SilentlyContinue)) { 15 | write-host $i.toupper() "is Unavalible" -foreground red 16 | "`r" 17 | } 18 | else { 19 | Write-host "Added $i to list...." 20 | $adsi = [ADSI]"WinNT://$i" 21 | 22 | $Object = $adsi.Children | ? {$_.SchemaClassName -eq 'user'} | % { 23 | $UserName = $_.Name -join ''; 24 | New-Object -TypeName PSCustomObject -Property @{ 25 | ComputerName = $i.toupper() -join '' 26 | UserName = $UserName 27 | Groups = ($_.Groups() |Foreach-Object {$_.GetType().InvokeMember("Name",'GetProperty', $null, $_, $null)}) -join ',' 28 | Disabled = (Get-WmiObject -ComputerName $i -Class Win32_UserAccount -Filter "LocalAccount='$true' and name='$UserName'"` 29 | |Select-Object -expandproperty Disabled) -join '' 30 | } 31 | } 32 | 33 | $Object | Select-object ComputerName,UserName,Groups,Disabled |? {$_.Groups -match "Administrators*"} 34 | "`r" 35 | } 36 | } 37 | } 38 | 39 | $admins = Get-AdminGroups -ErrorAction SilentlyContinue 40 | 41 | 42 | #built-in admin account not named "winroot" will be changed via group policy 43 | Function Remove-Admin{ 44 | 45 | foreach($admin in $admins){ 46 | #renames a local account named winroot that is not built-in then disables it. This is done so our GPO 47 | #will can rename the built-in admin account to winroot. 48 | if($admin.UserName -match "winroot" -and $admin.groups -match "Administrators,Users"){ 49 | $user = [ADSI]("WinNT://" + $($admin.computername) + "/$($admin.UserName),user") 50 | $user.psbase.rename("winroot_old") 51 | 52 | $user = [ADSI]("WinNT://" + $($admin.computername) + "/winroot_old") 53 | $user.UserFlags[0] = $User.UserFlags[0] -bor 0x2 54 | $user.SetInfo() 55 | 56 | Write-host $($admin.computername) "has been renamed to winroot_old" 57 | } 58 | 59 | #sets account password and disables all local accounts 60 | 61 | if($admin.UserName -notmatch "winroot"){ 62 | $user = [ADSI]("WinNT://" + $($admin.computername) + "/" + $($admin.UserName)) 63 | $user.UserFlags[0] = $User.UserFlags[0] -bor 0x2 64 | $user.SetInfo() 65 | Write-host "\\$($admin.computername)\$($admin.UserName) has been disabled `r" 66 | } 67 | 68 | 69 | #enables winroot built-in account if its disabled 70 | if($admin.UserName -match "winroot" -and $admin.groups -match "Administrators"){ 71 | $user = [ADSI]("WinNT://" + $($admin.computername) + "/winroot") 72 | $user.UserFlags[0] = $User.UserFlags[0] -bxor 0x2 73 | $user.SetInfo() 74 | Write-host "\\$($admin.computername)\winroot has been enabled" 75 | } 76 | } 77 | } 78 | 79 | Remove-Admin -ErrorAction SilentlyContinue 80 | -------------------------------------------------------------------------------- /local_security_policy_update.ps1: -------------------------------------------------------------------------------- 1 | <# .SYNOPSIS 2 | This script will remote into a machine and update the Local Security Policy, it will then change the permissions on 3 | a specified folder. The csv must have 2 coloumns one with SAMaccountName and the other with the users machines name. 4 | 5 | #> 6 | 7 | foreach($user in (Import-Csv C:\users\joeord\Desktop\user_machines.csv)){ 8 | 9 | 10 | $sid = (get-aduser $user.user).sid.value 11 | 12 | 13 | 14 | Invoke-Command $user.machine -ArgumentList $sid,$user{ 15 | param($sid, 16 | $user 17 | ) 18 | 19 | #sets local policy settings 20 | 21 | secedit /export /cfg c:\file1.inf 22 | 23 | 24 | Get-Content C:\file1.inf | 25 | % {$_ -replace "SeCreateGlobalPrivilege.*", "SeCreateGlobalPrivilege = *S-1-5-19,*S-1-5-20,*$($sid),*S-1-5-32-544,*S-1-5-6"} | 26 | Set-Content C:\file2.inf 27 | 28 | 29 | secedit /import /cfg C:\file2.inf /db C:\file2.sdb 30 | secedit /configure /db C:\file2.sdb 31 | Remove-Item C:\file2.sdb 32 | Remove-Item C:\file1.inf 33 | Remove-Item C:\file2.inf 34 | 35 | #looks for and sets folder permissions for folder you would like 36 | 37 | function find-path{ 38 | $fileName = "FolderName" 39 | Get-ChildItem -Force "c:\" -ErrorAction SilentlyContinue | 40 | ? { ($_.PSIsContainer -eq $true) -and ( $_.Name -like "*$fileName*") } | 41 | Select-Object -expand FullName 42 | } 43 | 44 | foreach($folder in find-path){ 45 | Write-Output "Setting permissions on $env:COMPUTERNAME for FolderName on $folder" 46 | $acl = Get-Acl $folder 47 | $myGroup = "CORPORATE\$($user.user)" 48 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "Write", "ContainerInherit, ObjectInherit", "None", "Allow") 49 | $acl.AddAccessRule($rule) 50 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "Read", "ContainerInherit, ObjectInherit", "None", "Allow") 51 | $acl.AddAccessRule($rule) 52 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "ReadAndExecute", "ContainerInherit, ObjectInherit", "None", "Allow") 53 | $acl.AddAccessRule($rule) 54 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "ListDirectory", "ContainerInherit, ObjectInherit", "None", "Allow") 55 | $acl.AddAccessRule($rule) 56 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "Modify", "ContainerInherit, ObjectInherit", "None", "Allow") 57 | $acl.AddAccessRule($rule) 58 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "FullControll", "ContainerInherit, ObjectInherit", "None", "Allow") 59 | $acl.AddAccessRule($rule) 60 | Set-Acl $folder $acl 61 | } 62 | 63 | 64 | 65 | 66 | 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /logon.ps1: -------------------------------------------------------------------------------- 1 | (Get-date -UFormat "%a %m/%d/%Y,%H:%M:%S"),$env:COMPUTERNAME,$env:USERNAME,$env:SESSIONNAME,$env:logonserver -join "," | 2 | Out-File "\\Path\to\Share\Logon.log" 3 | -------------------------------------------------------------------------------- /monitor_dns_changes.ps1: -------------------------------------------------------------------------------- 1 | #Get machines and date added from DNS and exports to CSV for comparison. 2 | 3 | <# Use this if your using windows 2008 or prior 4 | Function Get-DNSentry{ 5 | Get-WMIObject -Computer DNSServer -Namespace "root\MicrosoftDNS" -Class "MicrosoftDNS_AType" ` 6 | -Filter "ContainerName='contoso.local' and TimeStamp <> 0" ` 7 | |Select-Object OwnerName, IPAddress, @{n="Date";e={([datetime]"1.1.1601").AddHours($_.Timestamp)}} ` 8 | |sort Date ` 9 | |Export-Csv C:\temp\update.csv -NoTypeInformation 10 | } 11 | #> 12 | 13 | #Use this for Windows 2012 DNS server 14 | Function Get-DNSentry{ 15 | Get-DnsServerResourceRecord -zonename contoso.local |Select-Object Hostname, TimeStamp|sort Hostname | 16 | Export-Csv C:\Scripts\update.csv -NoTypeInformation 17 | } 18 | 19 | 20 | Get-DNSentry 21 | 22 | Function Compare-CSV { 23 | $baseline = 24 | $new = 25 | 26 | Compare-Object (Import-csv -Path C:\temp\baseline.csv -Header "Computername","IPAddress", "Date") (Import-csv -Path C:\temp\update2.csv -Header "Computername","IPAddress", "Date") -Property "Computername" -PassThru | 27 | ?{$_.SideIndicator -eq '=>'} | 28 | Select-Object "Computername", "IPAddress", "Date" 29 | } 30 | 31 | #Creates email 32 | Function Send-Email { 33 | Send-MailMessage -To joerod@contoso.com ` 34 | -from DNSAlerts@contoso.com -Body ($status| Format-Table| Out-String) -subject "DNS Change" -smtpserver stmpmailbox -priority High 35 | 36 | } 37 | 38 | #Only sends email if there is a change 39 | if (Compare-CSV -ne $null) { 40 | Send-Email 41 | } 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /move_ou_by_os.ps1: -------------------------------------------------------------------------------- 1 | <#this script will move a machine to the proper OU based on OS 2 | 3 | #> 4 | foreach ($machine in (Get-ADObject -SearchBase "OU=WIN7,DC=CONTOSO,DC=LOCAL" -Filter * -Properties * |select operatingSystem, DistinguishedName)){ 5 | if($machine.operatingSystem -match "Windows XP Professional"){ 6 | Move-ADObject -Identity $machine.DistinguishedName -TargetPath "OU=WINXP,DC=CONTOSO,DC=LOCAL" 7 | Write-Output "$machine has been moved" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /optional_features.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [Parameter(Position=0,mandatory=$true)] 3 | [string]$Hostname = $env:COMPUTERNAME 4 | ) 5 | 6 | gwmi win32_OptionalFeature -computername $Hostname ` 7 | | Where-Object {$_.installstate -eq 1} | Select-Object Caption |Sort caption 8 | 9 | -------------------------------------------------------------------------------- /ping_dns_name.ps1: -------------------------------------------------------------------------------- 1 | # this script will find any pingable machine in a specified range and then list the DNS name of that IP 2 | $ErrorActionPreference = "Stop" 3 | $ping = New-Object System.Net.NetworkInformation.Ping 4 | $i = 0 5 | 1..255 | foreach { $ip = "192.168.1.$_" 6 | $Res = $ping.send($ip) 7 | 8 | if ($Res.Status -eq "Success") 9 | { 10 | 11 | $result = $ip + " = Success" 12 | 13 | Write-Host $result 14 | 15 | try{ 16 | nslookup $ip | findstr Name: 17 | } 18 | 19 | catch { 20 | Write-Warning "$ip - Can't find DNS record" 21 | } 22 | $i++ 23 | } 24 | 25 | } 26 | $Hosts = [string]$i + " Hosts is pingable" 27 | Write-Host $Hosts 28 | 29 | #$error[0].Exception.GetType().FullName use to find the exact error powershell throws 30 | -------------------------------------------------------------------------------- /ps_googlemap_route.ps1: -------------------------------------------------------------------------------- 1 | <#I wrote this script with the intent of using it with my Raspberry Pi magic mirror 2 | this will get the travel details for me and my wife every morning. My wife drives to work 3 | so I'm using google maps API for driving. I take the subway so I'm using maps for transit. 4 | Just thinking it would be pretty cool to have this script running on Win10 core on the Pi for my magic mirror. 5 | #> 6 | 7 | $key = "" 8 | #Use Lat/Long coordinates here 9 | $home_addy = "" 10 | $dani_work = "" 11 | $joe_work = "" 12 | $momdad_addy = "" 13 | 14 | ###Danielle Driving to work Directions### 15 | ###Gets EPOC time for departure### 16 | $DateTime = Get-Date -Hour 21 -Minute 30 -Second 00 -Millisecond 00 17 | $Epoc = ([DateTimeOffset] $DateTime).ToUnixTimeSeconds() 18 | 19 | $result = Invoke-RestMethod -Uri "https://maps.googleapis.com/maps/api/directions/json?origin=$home_addy&destination=$dani_work&departure_time=$Epoc&key=$key" -Method Get 20 | $result.routes.legs.steps.html_instructions 21 | ########################################## 22 | 23 | ###Joe Subway directions### 24 | ###Gets EPOC time for departure### 25 | $DateTime = Get-Date -Hour 20 -Minute 30 -Second 00 -Millisecond 00 26 | $Epoc = ([DateTimeOffset] $DateTime).ToUnixTimeSeconds() 27 | 28 | $result = (Invoke-RestMethod -Uri "https://maps.googleapis.com/maps/api/directions/json?origin=$momdad_addy&destination=$joe_work&departure_time=$Epoc&mode=transit&key=$key" -Method Get).routes.legs.steps 29 | #lets me know what is the last train on my route so my print is "leave" or "transfer" 30 | $stops = ($result | ? { $_.travel_mode -eq "TRANSIT" })[-1].end_location 31 | $result | % { if ($_.travel_mode -eq "TRANSIT"){ 32 | Write-Host "Subway" -ForegroundColor Yellow 33 | Write-Output ("Enter at station: {0}" -f $_.transit_details.departure_stop.name) 34 | $_.html_instructions 35 | Write-Output ("Number of stops: {0}" -f $_.transit_details.num_stops) 36 | if ($stops -ne $_.end_location){ 37 | $status = "Transfer" 38 | } 39 | else { 40 | $status = "Leave" 41 | } 42 | Write-Output ("$status at station: {0}" -f $_.transit_details.arrival_stop.name) 43 | } 44 | 45 | 46 | else { 47 | Write-Host "Walking" -ForegroundColor Yellow 48 | $_.steps.html_instructions 49 | } 50 | } 51 | 52 | 53 | -------------------------------------------------------------------------------- /ps_prompt.ps1: -------------------------------------------------------------------------------- 1 | Install-Module -Name posh-git -Scope CurrentUser 2 | 3 | function prompt { 4 | $prompt = Write-Prompt ("PS {0}.{1} | " -f $PSVersionTable.PSVersion.Major,$PSVersionTable.PSVersion.Minor) 5 | $prompt += Write-Prompt "$([math]::round((((Get-History)[-1].EndExecutionTime - (Get-History)[-1].StartExecutionTime).TotalSeconds),3)) | " 6 | $prompt += & $GitPromptScriptBlock 7 | if ($prompt) {$prompt} else {" "} 8 | } 9 | -------------------------------------------------------------------------------- /pushbullet.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | This script sends push notifications via the PushBullet API 4 | 5 | .DESCRIPTION 6 | This function can be used to send push notifications. This script will likely grow to do more functions via the Pushbullet API. 7 | You must have a Pushbullet API key in order for this function to work. The link to create an access token is the following 8 | https://www.pushbullet.com/#settings/account 9 | 10 | .PARAMETER APIKey 11 | This parameter is required in order to connect to the Pushbullet API. 12 | 13 | .PARAMETER Message 14 | The message you wish to send to the PushBullet device 15 | 16 | .PARAMETER Device 17 | Specifiy which device you'd like to send to by using the device_iden string. If this isnt specified the push gets sent to all devices. 18 | 19 | .PARAMETER Url 20 | PushBullet API URL. This parameter is set to https://api.pushbullet.com/v2/pushes 21 | 22 | .EXAMPLE 23 | Send-PushBulletMessage -APIKey "*****" -Message "Str8 from PowerShell" 24 | 25 | .NOTES 26 | General notes 27 | #> 28 | 29 | Function Send-PushBulletMessage { 30 | param( 31 | [Parameter(Mandatory=$true)]$APIKey, 32 | [Parameter(Mandatory=$true)]$Message, 33 | [Parameter(Mandatory=$false)]$Device, 34 | [Parameter(Mandatory=$false)]$Url = "https://api.pushbullet.com/v2/pushes" 35 | ) 36 | $Body = @{ 37 | type = "note" 38 | title = $Message 39 | device_iden = $Device 40 | } 41 | $result = Invoke-WebRequest -Uri $URL -Method Post -Body $Body -Headers @{"Access-Token" = $APIKey} 42 | if($result.StatusCode -eq '200'){ 43 | Write-Output "Message Sucessfully Sent" 44 | } 45 | } 46 | 47 | #Send-PushBulletMessage -APIKey "" -Message "test" -Device "" 48 | 49 | Function Get-PushBulletDevices { 50 | param( 51 | [Parameter(Mandatory=$true)]$APIKey, 52 | [Parameter(Mandatory=$false)]$Url = "https://api.pushbullet.com/v2/devices" 53 | ) 54 | 55 | (Invoke-RestMethod -Uri $URL -Method Get -Headers @{"Access-Token" = $APIKey}).devices 56 | } 57 | 58 | #Get-PushBulletDevices -APIKey "" 59 | 60 | Function Get-WhoAmI { 61 | param( 62 | [Parameter(Mandatory=$true)]$APIKey, 63 | [Parameter(Mandatory=$false)]$Url = "https://api.pushbullet.com/v2/users/me" 64 | ) 65 | 66 | Invoke-RestMethod -Uri $URL -Method Get -Headers @{"Access-Token" = $APIKey} 67 | } 68 | 69 | #Get-WhoAmI -APIKey "" 70 | 71 | -------------------------------------------------------------------------------- /remove_dns.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | This script will query all the zones on a DNS server then remove entries based on a criteria in this case IP 4 | Addresses 5 | .EXAMPLE 6 | remove_dns.ps1 7 | #> 8 | 9 | foreach ($domainname in (Get-DnsServerZone -ComputerName crpnycdcrt01 | ? { ($_.IsReverseLookupzone -like "false") -and ($_.ZoneType -like "Primary") } | Select-Object -ExpandProperty ZoneName)) { 10 | function list { 11 | 12 | get-wmiobject -ComputerName dnsserver -Namespace root\microsoftDNS -Class MicrosoftDNS_ResourceRecord -Filter "domainname='$domainname'" | 13 | Select-Object IPAddress, ownername | 14 | Where-Object { ($_.IPAddress -match '10.7') -or ($_.IPAddress -match '10.9') -and ($_.IPAddress -notlike $null) } | 15 | Sort-Object IPAddress 16 | } 17 | 18 | ForEach ($ip in list) { 19 | $ipnew = $ip.ownername -replace "\..+" 20 | #Remove-DnsServerResourceRecord -ZoneName "corporate.local" -RRType "A" -Name $($ip.ownername) -RecordData $($ip.IPAddress) 21 | dnscmd crpnycdcrt01 /RecordDelete $domainname $ipnew A $ip.IPAddress /f 22 | Write-output "$ipnew $($ip.IPAddress) has been removed from DNS" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /remove_local_admin_domain_users.ps1: -------------------------------------------------------------------------------- 1 | #rewrote this script using invoke-command and net lcoalgroup cmd. Also added logging to each function 2 | 3 | Function Get-AdminGroups{ 4 | 5 | foreach($i in (Get-Content C:\Users\joerod\Desktop\remove_users.txt)){ 6 | 7 | #test if machine is on the network 8 | if (-not (Test-Connection -computername $i -count 1 -Quiet -ErrorAction SilentlyContinue)) { 9 | Write-Warning "$i is Unavalible" 10 | "`r" 11 | $i | Out-File C:\Script_logs\remove_local_admin_$(get-date -f MM-dd-yyyy).log -Append 12 | } 13 | else { 14 | $i | Out-File C:\Script_logs\remove_local_admin_$(get-date -f MM-dd-yyyy).log -Append 15 | Write-Output "Added $i to list...." 16 | (invoke-command { 17 | $members = net localgroup administrators | 18 | where {$_ -AND $_ -notmatch "command completed successfully"} | 19 | select -skip 4 20 | New-Object PSObject -Property @{ 21 | Computername = $env:COMPUTERNAME 22 | Group = "Administrators" 23 | Users=$members 24 | } 25 | } -computer $i -HideComputerName | 26 | Select * -ExcludeProperty RunspaceID ) 27 | } 28 | } 29 | } 30 | $admins = Get-AdminGroups 31 | 32 | 33 | Function Remove-Admin{ 34 | 35 | foreach($admin in $admins){ 36 | 37 | 38 | #deletes local accounts if conditions are met 39 | for($i=0;$i -lt $admin.users.count;$i++){ 40 | if(($admin.users[$i] -ne "contoso\Domain Admins") -and ($admin.users[$i] -notlike "contoso\WkstPerm*") -and ($admin.users[$i] -notlike "administrator") -and ($admin.users[$i] -ne $null)){ 41 | 42 | #Add user to Remote Desktop Users Group 43 | Try{ 44 | # adds logged in use to remote desktop users group 45 | $logoff_user = gwmi -computername $($admin.computername) -class win32_computersystem |select -ExpandProperty UserName 46 | if($logoff_user -ne $null){ 47 | $scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("NET LOCALGROUP 'Remote Desktop Users' $logoff_user /add") 48 | Invoke-Command -ComputerName $($admin.computername) -ScriptBlock $scriptblock -ErrorAction Stop -ErrorVariable remotedesktop 49 | } 50 | } 51 | Catch{ 52 | Write-Warning "$($admin.users[$i]) is already a member of the remote users group." #| Out-File C:\Script_logs\remove_local_admin$(get-date -f MM-dd-yyyy).log -append 53 | 54 | } 55 | 56 | Try{ 57 | # add users who are in admin group to remote admin group 58 | $scriptblock2 = $ExecutionContext.InvokeCommand.NewScriptBlock("NET LOCALGROUP 'Remote Desktop Users' $($admin.users[$i]) /add") 59 | Invoke-Command -ComputerName $($admin.computername) -ScriptBlock $scriptblock2 -ErrorAction Stop -ErrorVariable remotedesktop 60 | Write-Output "Add $($admin.users[$i]) to Remote Desktop Users group on $($admin.computername)`r" #|Out-File C:\Script_logs\remove_local_admin.log -Append 61 | $remotedesktop | Out-File C:\Script_logs\remove_local_admin_$(get-date -f MM-dd-yyyy).log -append 62 | } 63 | Catch{ 64 | Write-Warning "$($admin.users[$i]) is already a member of the remote users group." #| Out-File C:\Script_logs\remove_local_admin_$(get-date -f MM-dd-yyyy).log -append 65 | $($admin.users[$i]) | Out-File C:\Script_logs\remove_local_admin_$(get-date -f MM-dd-yyyy).log -append 66 | } 67 | 68 | #Removes user from Administrators Group 69 | $scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("NET LOCALGROUP administrators $($admin.users[$i]) /delete") 70 | Invoke-Command -ComputerName $($admin.computername) -ScriptBlock $scriptblock ErrorVariable $admingroup 71 | Write-Output "Delete $($admin.users[$i]) from Administrators group on $($admin.computername)`r" #|Out-File C:\Script_logs\remove_local_admin_$(get-date -f MM-dd-yyyy).log -Append 72 | 73 | 74 | 75 | } 76 | } 77 | #Logs off user 78 | Try{ 79 | Invoke-Command -ComputerName $($admin.computername) { (gwmi win32_operatingsystem).Win32Shutdown(4) |Out-Null} -ErrorAction Stop -ErrorVariable logoff 80 | Write-Output "Logging off $logoff_user" #|Out-File C:\Script_logs\remove_local_admin_$(get-date -f MM-dd-yyyy).log -Append 81 | } 82 | Catch{ 83 | Write-Output "Cannot log off $logoff_user" #|Out-File C:\Script_logs\remove_local_admin_$(get-date -f MM-dd-yyyy).log -Append 84 | } 85 | } 86 | } 87 | 88 | 89 | Remove-Admin 90 | -------------------------------------------------------------------------------- /remove_manager.ps1: -------------------------------------------------------------------------------- 1 | #searches AD for users who are not enabled and removes their manager 2 | #What are we doing here??? I can make this better and less code. 3 | 4 | foreach($user in (get-aduser -filter *)){ 5 | $account = get-aduser $user -Properties enabled, manager 6 | if($account.enabled -eq $false -and $account.manager -ne $null){ 7 | Write-Output "Working on $($account.name)" 8 | set-aduser $account -Manager $null 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /remove_null_groups.ps1: -------------------------------------------------------------------------------- 1 | #This script finds empty groups in the OU listed in the 4th line 2 | 3 | function empty_groups{ 4 | Get-ADGroup -Filter {GroupCategory -eq 'Security'} -SearchBase "OU=Empty,DC=contoso, DC=local" | 5 | {@(Get-ADGroupMember $_).Length -eq 0} | 6 | Select-Object -expandproperty Distinguishedname 7 | } 8 | 9 | foreach($i in empty_groups){ 10 | 11 | #shows progress of script 12 | Write-Output $i 13 | 14 | #removes accidental deletion of object 15 | Set-ADObject $i -ProtectedFromAccidentalDeletion $false 16 | 17 | #removes the object from AD 18 | Remove-ADGroup -Identity $i -confirm:$false 19 | 20 | } 21 | -------------------------------------------------------------------------------- /remove_rename_unjoin.ps1: -------------------------------------------------------------------------------- 1 | <#This script will remove some software, in this case SEP, change the local admin account name from "root" to "administrator", 2 | change the local administrators password, and finally unjoin the machine from the domain. 3 | #> 4 | 5 | $cred = Get-Credential 6 | 7 | foreach($computer in (get-content c:\list.txt)){ 8 | 9 | #test if computer is alive (pingable) 10 | if (-not (Test-Connection -computername $computer -count 1 -Quiet -ErrorAction SilentlyContinue)) { 11 | Write-Warning "$computer is Unavalible" 12 | $computer | Out-File C:\Users\joerod\Desktop\bad_desktop.log -Append 13 | } 14 | 15 | else { 16 | Write-Output "Added $computer to working list...." 17 | $computer |Out-File C:\Users\joerod\Desktop\good_desktop.log -Append 18 | 19 | #removes SEP 20 | Write-Output "Starting SEP removal..." 21 | $myses = New-PSSession -ComputerName $computer 22 | Invoke-Command -Session $myses -ScriptBlock { 23 | 24 | $find_sep = gwmi win32_product -filter "Name LIKE '%Endpoint Protection%'" | select -ExpandProperty IdentifyingNumber 25 | foreach($i in $find_sep){ 26 | msiexec.exe /x $i /qn /passive /l*v! c:\uninst.log 27 | } 28 | } -ErrorVariable removeapp_error 29 | 30 | #wait 2.5 minute for SEP to uninstall 31 | Write-Output "Waiting for SEP to uninstall" 32 | Start-Sleep -s 150 33 | 34 | Invoke-Command -ComputerName $computer -Verbose -ScriptBlock { 35 | 36 | #rename local admin account to Administrator 37 | Write-Output "Renaming Local Admin Account..." 38 | $newname = "Administrator" 39 | $user = Get-WMIObject Win32_UserAccount -Filter "Name='Root'" 40 | $user.Rename($newName) |Out-Null 41 | 42 | #resets local admin password 43 | Write-Output "Changing Local Password..." 44 | $newpassword = "ChangeMe!" 45 | $user = [ADSI]"WinNT://./$newName" 46 | $user.SetPassword("$newpassword") 47 | 48 | 49 | } -ErrorVariable tasks_error 50 | 51 | 52 | $session = $computer |New-PSSession -Credential $cred 53 | Invoke-Command -Session $session -Verbose -ScriptBlock { param($cred) 54 | Write-Output "Unjoining from Domain..." 55 | Remove-Computer -UnjoinDomainCredential $cred -Passthru -force -Restart 56 | } -ArgumentList $cred -ErrorVariable tasks_error 57 | 58 | } 59 | } 60 | 61 | $removeapp_error | Out-File C:\Users\joerod\Desktop\desktop.log -Append 62 | $tasks_error | Out-File C:\Users\joerod\Desktop\desktop.log -Append 63 | -------------------------------------------------------------------------------- /remove_user_session.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [CmdletBinding()] 3 | [Parameter(ValueFromPipeline=$true, 4 | ValueFromPipelineByPropertyName=$true)] 5 | [string[]]$ComputerName = 'localhost' 6 | ) 7 | 8 | process { 9 | foreach ($Computer in $ComputerName) { 10 | quser /server:$Computer | Select-Object -Skip 1 | % { 11 | $CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s' 12 | $HashProps = @{ 13 | UserName = $CurrentLine[0] 14 | ComputerName = $Computer 15 | } 16 | 17 | # If session is disconnected different fields will be selected 18 | if ($CurrentLine[2] -eq 'Disc') { 19 | $HashProps.SessionName = $null 20 | $HashProps.Id = $CurrentLine[1] 21 | $HashProps.State = $CurrentLine[2] 22 | $HashProps.IdleTime = $CurrentLine[3] 23 | $HashProps.LogonTime = $CurrentLine[4..6] -join ' ' 24 | } else { 25 | $HashProps.SessionName = $CurrentLine[1] 26 | $HashProps.Id = $CurrentLine[2] 27 | $HashProps.State = $CurrentLine[3] 28 | $HashProps.IdleTime = $CurrentLine[4] 29 | $HashProps.LogonTime = $CurrentLine[5..7] -join ' ' 30 | } 31 | 32 | New-Object -TypeName PSCustomObject -Property $HashProps | 33 | Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime 34 | } 35 | } 36 | 37 | 38 | 39 | 40 | $session = Read-host 'Would you like to log off a session? Enter No or enter Session ID ' 41 | if($session -eq 'No'){ 42 | Write-output "Goodbye" 43 | } 44 | 45 | else{ 46 | LOGOFF $session /server:$ComputerName 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /samaccount_from_real_name.ps1: -------------------------------------------------------------------------------- 1 | #find users samaccount name from real name 2 | import-module ActiveDirectory 3 | param 4 | ( 5 | 6 | [Parameter(Mandatory=$true)] [string]$Name, 7 | [switch]$All 8 | ) 9 | 10 | if($all){ 11 | $user = Get-ADUser -Filter "Name -like '$Name*'" -Properties * | Select-Object Name, SamAccountName, Mail, Enabled 12 | if($user -eq $null){ 13 | Write-Output "$name cannot be found" 14 | 15 | } 16 | else { 17 | $user 18 | } 19 | } 20 | 21 | else { 22 | $user = Get-ADUser -Properties * -Filter "Name -like '$Name*'" | ? {$_.Enabled -contains "True"} | Select-Object Name, SamAccountName, Mail 23 | if($user -eq $null){ 24 | Write-Output "$name cannot be found" 25 | 26 | } 27 | else { 28 | $user 29 | } 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /signature.ps1: -------------------------------------------------------------------------------- 1 | #set this to the location of the gam binaries 2 | Set-Alias gam C:\gam\gam.exe 3 | 4 | #Imports data from a csv that has coloumns listed as below. Manditory prepopulated coloums for this script to work are email first last 5 | $salesou = Import-Csv C:\scripts\sales.csv 6 | foreach($column in $salesou) 7 | { 8 | $field1 = $column.email 9 | $field2 = $column.first 10 | $field3 = $column.last 11 | $field4 = $column.title 12 | $field5 = $column.mobile 13 | $field6 = $column.desk 14 | $field7 = $column.link1 15 | $field8 = $column.url1 16 | $field9 = $column.link2 17 | $field10 = $column.url2 18 | $field11 = $column.link3 19 | $field12 = $column.url3 20 | $field13 = $column.link4 21 | $field14 = $column.url4 22 | $field15 = $column.link5 23 | $field16 = $column.url5 24 | $field17 = $column.link6 25 | $field18 = $column.url6 26 | $field19 = $column.link7 27 | $field20 = $column.url7 28 | 29 | #prepends | o: string if user has mobile and desk number 30 | $prepend = $null; 31 | if(![string]::IsNullOrEmpty($field6)) { $prepend = "| o: "; } 32 | $field6 = $prepend + $column.desk 33 | 34 | #sets the url link for the Patch Town if one exists 35 | $url1 = $null 36 | if(![string]::IsNullOrEmpty($field7)) {$url1 = "$field7"} 37 | $url2 = $null 38 | if(![string]::IsNullOrEmpty($field9)) {$url2 = "$field9"} 39 | $url3 = $null 40 | if(![string]::IsNullOrEmpty($field11)){$url3 = "$field11"} 41 | $url4 = $null 42 | if(![string]::IsNullOrEmpty($field13)){$url4 = "$field13"} 43 | $url5 = $null 44 | if(![string]::IsNullOrEmpty($field15)){$url5 = "$field15"} 45 | $url6 = $null 46 | if(![string]::IsNullOrEmpty($field17)){$url6 = "$field17"} 47 | $url7 = $null 48 | if(![string]::IsNullOrEmpty($field19)){$url7 = "$field19"} 49 | 50 | #prepends | charecter to Patch Town url variable if not null 51 | $prepend = $null; 52 | if(![string]::IsNullOrEmpty($field7)) { $prepend = "| "; } 53 | $link1 = $prepend + $url1 54 | 55 | $prepend = $null; 56 | if(![string]::IsNullOrEmpty($field9)) { $prepend = "| "; } 57 | $link2 = $prepend + $url2 58 | 59 | $prepend = $null; 60 | if(![string]::IsNullOrEmpty($field11)) { $prepend = "| "; } 61 | $link3 = $prepend + $url3 62 | 63 | $prepend = $null; 64 | if(![string]::IsNullOrEmpty($field13)) { $prepend = "| "; } 65 | $link4 = $prepend + $url4 66 | 67 | $prepend = $null; 68 | if(![string]::IsNullOrEmpty($field15)) { $prepend = "| "; } 69 | $link5 = $prepend + $url5 70 | 71 | $prepend = $null; 72 | if(![string]::IsNullOrEmpty($field17)) { $prepend = "| "; } 73 | $link6 = $prepend + $url6 74 | 75 | $prepend = $null; 76 | if(![string]::IsNullOrEmpty($field19)) { $prepend = "| "; } 77 | $link7 = $prepend + $url7 78 | 79 | $html = @" 80 | $field2 $field3
81 | $field4
82 | c: $field5 $field6
83 |
84 | Company tag line
85 | $link1 $link2 $link3 $link4 $link5 $link6 $link7
86 | "@ 87 | 88 | gam user $field1 signature "$html" 89 | 90 | } 91 | -------------------------------------------------------------------------------- /terminated_user.ps1: -------------------------------------------------------------------------------- 1 | #Runs check to make sure AD Module and Exchange plugins are isntalled 2 | Function Get-MyModule 3 | { 4 | if(-not(Get-Module -name "ActiveDirectory")) { 5 | try 6 | { 7 | Import-Module ActiveDirectory -ErrorAction Stop 8 | } 9 | catch{ 10 | Write-Output "Please install Windows Server Administrator tools" 11 | } 12 | } 13 | } 14 | Get-MyModule 15 | 16 | if ((Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.e2010 -ErrorAction SilentlyContinue) -eq $null){ 17 | 18 | try{ 19 | add-pssnapin Microsoft.Exchange.Management.PowerShell.e2010 -ErrorAction Stop 20 | } 21 | 22 | Catch{ 23 | Write-Output "Please install EMC for Exchange 2010" 24 | } 25 | } 26 | 27 | 28 | ##### Start Main Script ##### 29 | 30 | Param( 31 | [string]$termuser 32 | ) 33 | 34 | ##### AD processes ##### 35 | 36 | Function Disable-User{ 37 | #disable user 38 | Disable-ADAccount -Identity $termuser 39 | Write-Output "* $termuser has been disabled" 40 | } 41 | 42 | Function Reset-password{ 43 | #creates random 10 charecter password 44 | $randomObj = New-Object System.Random 45 | $NewPassword="" 46 | 1..10 | ForEach { $NewPassword = $NewPassword + [char]$randomObj.next(33,126) } 47 | Set-ADAccountPassword -Identity $termuser -Reset -NewPassword -NewPassword (ConvertTo-SecureString -AsPlainText $NewPassword -Force) 48 | Write-Output "* Password reset to $NewPassword" 49 | } 50 | 51 | Function Remove-Groups{ 52 | #removes from all distribution groups 53 | $dlists =(Get-ADUser $termuser -Properties memberof | select -expand memberof) 54 | foreach($dlist in $dlists){Remove-ADGroupMember $termuser -Identity $dlist -Confirm:$False} 55 | Write-Output "* Removed $termuser from $dlists" 56 | } 57 | 58 | Function MoveOU{ 59 | #Move to "Disabled Users" OU 60 | Move-ADObject -Identity $termuser -TargetPath 'OU=Disabled,OU=Users,DC=CONTOSO,DC=LOCAL' 61 | Write-Output "* $termuser moved to Disabled Users" 62 | } 63 | 64 | Function Remove-Manager{ 65 | #Removes manager from AD profile 66 | $findoldmanager = Get-ADUser $termuser -Properties * |select -ExpandProperty Manager 67 | $oldmanager = Get-ADUser $findoldmanager |select -ExpandProperty Name 68 | Set-ADUser $termuser -Manager $null 69 | Write-Output "* Removed manager $oldmanager from $termuser" 70 | } 71 | 72 | Function Get-TermTimestamp{ 73 | #Time stamp added to AD user account 74 | $terminatedby = $env:username 75 | $termDate = get-date -uformat "%m/%d/%y" 76 | $termUserDesc = "Terminated " + $termDate + " - " + $terminatedby 77 | set-ADUser $termuser -Description $termUserDesc 78 | write-output "* $termuser description set to $termUserDesc" 79 | } 80 | 81 | ##### Mailbox and OCS processes ##### 82 | 83 | Function Set-MailboxHidden{ 84 | #Hides user from Outlook GAL 85 | Set-Mailbox -identity $termuser -HiddenFromAddressListsEnabled $true 86 | Write-Output "* $termuser Has been removed from GAL" 87 | } 88 | 89 | Function Move-disabledMB{ 90 | #Moves mailbox to disabled mailbox DisabledUserMailbox 91 | $oldmailbox = Get-Mailbox -Identity $termuser |select -ExpandProperty servername 92 | New-MoveRequest -Identity $termuser -TargetDatabase 'DisabledUserMailbox' 93 | Write-Output "* $termuser has been moved from $oldmailbox.toupper() to DisabledUserMailbox" 94 | } 95 | 96 | Function Disable-OCS{ 97 | #Disables users account in OCS 98 | Set-ADUser -Identity $termuser -clear msRTCSIP-UserEnabled 99 | Set-ADUser -Identity $termuser -clear msRTCSIP-PrimaryHomeServer 100 | Set-ADUser -Identity $termuser -clear msRTCSIP-PrimaryUserAddress 101 | Set-ADUser -Identity $termuser -clear msRTCSIP-OptionFlags 102 | Write-Output "* $termuser OCS has been disabled" 103 | } 104 | 105 | Disable-User 106 | Reset-password 107 | MoveOU 108 | Remove-Groups 109 | Remove-Manager 110 | Set-MailboxHidden 111 | Move-disabledMB 112 | Disable-OCS 113 | Get-TermTimestamp 114 | -------------------------------------------------------------------------------- /test.ps1: -------------------------------------------------------------------------------- 1 | $urls = @{ 2 | "http://64.52.85.212/nextcloud/index.php/s/NOpoQiFrr9RPh4M/download?path=%2FStandard%20Snake%2F12%20Team%2F0.5%20PPR%2F1%20QB&files=2017-08-04%2012%20TM%200.5%20PPR%201QB%202RB%203WR%201TE%201FLX%206%20PaTD%20Snake.","C:\Users\joerod\Dropbox\Fantasy\2017\CBS\2017-08-04 12 TM 0.5 PPR 1QB 2RB 2WR 1TE 1FLX 4 PaTD Snake." 3 | "http://64.52.85.212/nextcloud/index.php/s/NOpoQiFrr9RPh4M/download?path=%2FStandard%20Snake%2F12%20Team%2F0%20PPR%2F1%20QB&files=2017-08-04%2012%20TM%200%20PPR%201QB%202RB%203WR%201TE%201FLX%204%20PaTD%20Snake." =,"C:\Users\joerod\Dropbox\Fantasy\2017\ESPN\2017-08-04 12 TM 0 PPR 1QB 2RB 2WR 1TE 1FLX 4 PaTD Snake" 4 | } 5 | 6 | Write-Output pdf,xlsx | ForEach-Object {Invoke-WebRequest -Uri ($url + $_) -OutFile ( + $_)} 7 | 8 | $api = "o.kHVT1FpJBxTmasHW8U4BN1HyPVRPnBVP" 9 | $PushURL = "https://api.pushbullet.com/v2/pushes" 10 | $devices = "https://api.pushbullet.com/v2/devices" -------------------------------------------------------------------------------- /test_questions.psm1: -------------------------------------------------------------------------------- 1 | #Was thinking about PowerShell questions to ask on an interview and I came up with these. 2 | 3 | #How do i know if a number is negative or positive 4 | Function Get-NegativeOrPositive([int]$Number){ 5 | if($Number -gt 0){Write-Output "Postive"} else{Write-Output "Negative"} 6 | } 7 | 8 | #Get-NegativeOrPositive -Number '-1' 9 | #How do i know if a number is even or odd 10 | Function Get-EvenOrOdd([int]$Number){ 11 | if($Number%2 -eq 0){Write-Output "Even"} else{Write-Output "Odd"} 12 | } 13 | 14 | # Get-EvenOrOdd -Number '-2' 15 | -------------------------------------------------------------------------------- /update_dfsn_fqdn.ps1: -------------------------------------------------------------------------------- 1 | foreach ($dfsn in (Get-DfsnFolder -Path '\\contoso.corp\Network\*' | Get-DfsnFolderTarget | ? { $_.targetpath -notlike "*contoso.corp*" -and $_.targetpath -notlike "*10.*" -and $_.state -like "online" } | select Path, TargetPath)){ 2 | #Formats and adds the FQDN to DFSN Path 3 | $new_targetpath = $dfsn.targetpath.Replace(([regex]::match("$($dfsn.targetpath)", '[^\\]+’).value), (([regex]::match("$($dfsn.targetpath)", '[^\\]+’).value) + (".contoso.corp"))) 4 | New-DfsnFolderTarget -Path $dfsn.path -TargetPath $new_targetpath -Confirm:$false 5 | #Removes old dfs share 6 | Remove-DfsnFolderTarget -Path $dfsn.path -TargetPath $dfsn.targetpath -Confirm:$false 7 | } 8 | -------------------------------------------------------------------------------- /userlogin_query.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [Parameter(Position=0,mandatory=$true)] 3 | [string]$Username, 4 | [switch]$Last 5 | ) 6 | 7 | $array = Import-Csv \\share\Logon.log | ? {$_.username -eq $Username} | % { 8 | 9 | New-Object -TypeName PSCustomObject -Property @{ 10 | ComputerName = $_.computername 11 | "Logon Date" = $_.date 12 | } 13 | } 14 | 15 | 16 | if($Last){ 17 | 18 | $array[-1] 19 | } 20 | 21 | else 22 | { 23 | $array 24 | } 25 | -------------------------------------------------------------------------------- /vm_hdd_resize.ps1: -------------------------------------------------------------------------------- 1 | 2 | <#This script will resize a esx vmware host hdd then extend the hdd on the machine itself. 3 | Prerequisits are Windows 7 and above and Windows 2008 and above, WinRM must also be enabled on the host machines. 4 | #> 5 | Function VMHDDResize { 6 | Param( 7 | [Parameter(mandatory)] 8 | [string]$ComputerName, 9 | [Parameter(mandatory)] 10 | [int]$NewSize 11 | ) 12 | 13 | $VMHDD = Get-HardDisk -vm $ComputerName | where-object {$_.Name -eq "hard disk 1"} 14 | 15 | Set-HardDisk -harddisk $VMHDD -CapacityGB (([int]$vmhdd.CapacityGB) + ([int]$newsize)) -Confirm:$false 16 | 17 | Invoke-Command -ComputerName $ComputerName -ScriptBlock {"rescan","select volume 2","extend" | diskpart} 18 | } 19 | --------------------------------------------------------------------------------