Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: TechAbib/Random-PowerShell-Work
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: adbertram/Random-PowerShell-Work
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
Able to merge. These branches can be automatically merged.
Loading
Showing with 3,288 additions and 561 deletions.
  1. +217 −0 APIs/Get-TwitterFollowers.ps1
  2. +168 −0 AWS/Lambda/PowerShellFunction-IAMRole-demo.ps1
  3. +185 −0 ActiveDirectory/Check-HomeDriveConsistency/Check-HomeDriveConsistency.ps1
  4. +12 −0 ActiveDirectory/Check-HomeDriveConsistency/config.xml
  5. +139 −0 ActiveDirectory/Get-ActiveDirectoryUserNameMatch.ps1
  6. +19 −24 ActiveDirectory/Get-GPO-Reg-Settings.ps1
  7. +105 −91 ActiveDirectory/Get-UserLogonSessionHistory.ps1
  8. +16 −18 ActiveDirectory/TestSiteReplicationMod.ps1
  9. +647 −0 Ansible/Ansible.psm1
  10. BIN Article Examples/Firewall Rules from text file.xlsx
  11. +463 −0 Article Examples/cloudinsights-windows.ps1
  12. +84 −95 Azure/Remove-AzrVirtualMachine.ps1
  13. +0 −1 DNS/Get-RecordsToBeScavenged.ps1
  14. +29 −134 DNS/Resolve-DdnsRecordPermissionProblem.ps1
  15. +61 −0 Desktop/Remove-Win10-Apps.ps1
  16. +2 −2 File-Folder Management/Invoke-WindowsDiskCleanup.ps1
  17. +41 −0 Group Policy/User Logon Scripts/Set-WinProfilePhotoFromAD.ps1
  18. +35 −0 MDT/Install-Drivers.ps1
  19. +22 −0 Networking/connect-vpn.ps1
  20. +39 −43 PowerShell Gallery/Publish-PowerShellGalleryModule.ps1
  21. +46 −30 PowerShell Internals/New-DynamicParam.ps1
  22. +61 −50 Processes/Invoke-Process.ps1
  23. +93 −0 Random Stuff/New-Employee.ps1
  24. +203 −56 Random Stuff/Test-PendingReboot.ps1
  25. +19 −17 Registry/Set-RegistryValueForAllUsers.ps1
  26. +102 −0 SCCM/Get-SCCMClientLog.ps1
  27. +78 −0 Security/Test-UserAccountPassword.ps1
  28. +70 −0 Software/Get-MSIDatabaseProperties.ps1
  29. +176 −0 Software/Remove-Software.ps1
  30. +35 −0 java/cleanup.ps1
  31. +56 −0 mini-course/Get-ServerInformation.ps1
  32. +65 −0 mini-course/Get-ServerInformation2.0.ps1
217 changes: 217 additions & 0 deletions APIs/Get-TwitterFollowers.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
[CmdletBinding()]
param(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$SeedScreenName,

[Parameter()]
[ValidateNotNullOrEmpty()]
[string[]]$NeverFollow = @('adbertram')
)
# $OAuthSettings = @{
# ApiKey = ''
# ApiSecret = ''
# AccessToken = ''
# AccessTokenSecret = ''
# }
# Set-TwitterOAuthSettings @OAuthSettings

# #requires -Module PSTwitterApi

function Show-Countdown {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[int]$MaxWaitMin
)

$timer = [system.diagnostics.stopwatch]::StartNew()
do {
$totalMinsWaited = [math]::Round($timer.Elapsed.TotalMinutes, 0)
Write-Host "$($MaxWaitMin - $totalMinsWaited)..." -NoNewline
Start-Sleep -Seconds 60
} while ($timer.Elapsed.TotalMinutes -lt $MaxWaitMin)

$timer.Stop()
}

function Get-FriendlyApiErrorResponse {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.ErrorRecord]$ErrorResponse
)
if ($ErrorResponse.Exception.Message -match 'You are unable to follow more people at this time') {
$ErrorResponse.Exception.Message
} else {
($ErrorResponse.ErrorDetails.Message | ConvertFrom-Json).errors.message
}
}

function Test-ApiRateLimitResponse {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ErrorResponse
)

$ErrorResponse -match '(Too many requests)|(Rate limit exceeded)'
}

function Get-TwitterFollowers {
[CmdletBinding()]
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$ScreenName,

[Parameter()]
[ValidateNotNullOrEmpty()]
[int]$RetryInterval = 15
)

do {
try {
$getFollowParams = @{
ErrorAction = 'Stop'
count = 200
}
if ($PSBoundParameters.ContainsKey('ScreenName')) {
$getFollowParams.screen_name = $ScreenName
}
if (Get-Variable -Name 'response' -ErrorAction 'Ignore') {
$getFollowParams.cursor = $response.next_cursor
}
if ($response = Get-TwitterFollowers_List @getFollowParams) {
Write-Verbose -Message "Get-TwitterFollowers: Retrieved $($response.users.Count) followers from user $ScreenName..."
$response.users

}
} catch {
$errResponse = Get-FriendlyApiErrorResponse -ErrorResponse $_
if (Test-ApiRateLimitResponse -ErrorResponse $errResponse) {
Write-Host "Hit API rate limit. Waiting $RetryInterval minutes..."
Show-Countdown -MaxWaitMin $RetryInterval
} else {
throw $errResponse
}
}
} while ($response.next_cursor)
}

function Get-MyTwitterFriends {
## Users I'm following
[CmdletBinding()]
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[int]$RetryInterval = 15 ## minutes
)

do {
try {
$getTwitterFriendsParams = @{
count = 200
ErrorAction = 'Stop'
}
if (Get-Variable -Name 'response' -ErrorAction 'Ignore') {
$getTwitterFriendsParams.cursor = $response.next_cursor
}
if ($response = Get-TwitterFriends_List @getTwitterFriendsParams) {
Write-Verbose -Message "Retrieved $($response.users.Count) friends from API call..."
$response.users
}
} catch {
$errResponse = Get-FriendlyApiErrorResponse -ErrorResponse $_
if (Test-ApiRateLimitResponse -ErrorResponse $errResponse) {
Write-Host 'Hit API rate limit. Waiting...'
Show-Countdown
} else {
throw $errResponse
}
}
} while ($response.next_cursor)
}

function Follow-TwitterUser {
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ScreenName,

[Parameter()]
[ValidateNotNullOrEmpty()]
[int]$RetryInterval = 15, ## minutes

[Parameter()]
[ValidateNotNullOrEmpty()]
[int]$MaxRetries = 5
)

$retriesPerformed = 0
$success = $false
do {
try {
$followParams = @{
ErrorAction = 'Stop'
screen_name = $ScreenName
}
Write-Verbose -Message "Attempting to follow screen name $ScreenName..."
$response = Send-TwitterFriendships_Create @followParams
Write-Verbose -Message 'Successfully followed user.'
$success = $true
} catch {
$errResponse = Get-FriendlyApiErrorResponse -ErrorResponse $_
if (Test-ApiRateLimitResponse -ErrorResponse $errResponse) {
$retriesPerformed++
if ($retriesPerformed -le $MaxRetries) {
Write-Host "Hit API rate limit. Waiting $RetryInterval minutes..."
Show-Countdown -MaxWaitMin $RetryInterval
} else {
throw $errResponse
}
} else {
throw $errResponse
}
}
} while (-not $success)
}

$profileDescKeywords = @('sccm', 'powershell', 'geek', 'engineer', 'azure', 'cloud', 'devops', 'admin', 'mcp', 'microsoft', 'aws', ' IT ', 'SQL')

# $myExistingFollowerScreenNames = (Get-TwitterFollowers).users.screen_name

foreach ($user in $SeedScreenName) {
try {
## filter unwanted users
<#
- following target screen name
- is not protected
- is not following me
- I am not following them
- they have a profile
- does not have a default profile image
- has at least one keyword in list in profile
#>
Get-TwitterFollowers -ScreenName $user -Verbose:$VerbosePreference | where {
$desc = $_.description;
-not $_.protected -and ## is not a protected account
-not $_.following -and ## I am not following them already
-not $_.followed_by -and ## They are not following me
$_.description -and ## They have a profile
$_.profile_image_url -notmatch 'default_profile_images' -and ## They don't have a default profilate image
($profileDescKeywords | ? { $desc -match $_ }) -and ## They have at least one interesting word in their profile
$_.screen_name -notin $NeverFollow
} | foreach {
Follow-TwitterUser -ScreenName $_.screen_name -Verbose:$VerbosePreference
}
} catch {
throw $_.Exception.Message
}
}
Write-Verbose -Message 'Twitter following complete.'
168 changes: 168 additions & 0 deletions AWS/Lambda/PowerShellFunction-IAMRole-demo.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
# Prepare the S3 Bucket
$bucket = New-S3Bucket -BucketName "NameOfYourBucket"
Add-S3PublicAccessBlock -BucketName $bucket.BucketName -PublicAccessBlockConfiguration_BlockPublicAcl $true -PublicAccessBlockConfiguration_BlockPublicPolicy $true -PublicAccessBlockConfiguration_IgnorePublicAcl $true -PublicAccessBlockConfiguration_RestrictPublicBucket $true
Write-S3BucketVersioning -BucketName $bucket.BucketName -VersioningConfig_Status "Enabled"

# Lambda Function Role
$policy = @"
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
"@
$role = New-IAMRole -RoleName "ROLE-RoleManager" -AssumeRolePolicyDocument $policy
$policy = @"
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": "iam:*",
"Resource": "*"
}
]
}
"@
Write-IAMRolePolicy -RoleName "ROLE-RoleManager" -PolicyDocument $policy -PolicyName "POLICY-ROLE-RoleManager"
Register-IAMRolePolicy -RoleName "ROLE-RoleManager" -PolicyArn "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
# Bucket Policy
$policy = @"
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": [
"$($role.Arn)"
]
},
"Action": [
"s3:*"
],
"Resource": [
"arn:aws:s3:::$($bucket.BucketName)",
"arn:aws:s3:::$($bucket.BucketName)/*"
]
}
]
}
"@
Write-S3BucketPolicy -BucketName $($bucket.BucketName) -Policy $policy
# Create the Lambda Function
New-AWSPowerShellLambda -ScriptName FUNCTION-RoleManager-1 -Template Basic
$function = @"
`$objects = Get-S3Object -BucketName $($bucket.BucketName)
foreach(`$object in `$objects)
{
`$firstSlash = `$object.Key.IndexOf("/")
`$secondSlash = `$object.Key.IndexOf("/",`$firstSlash+1)-`$firstSlash-1
`$entity = `$object.Key.Substring(0,`$firstSlash)
`$roleName = `$object.Key.Substring(`$firstSlash+1,`$secondSlash)
`$policyName = `$object.Key.Substring(`$firstSlash+`$secondSlash+2,`$object.Key.IndexOf(".")-`$firstSlash-`$secondSlash-2)
if(`$entity -match "^[0-9]{12}$")
{
`$policy = @'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"AWS": "`$entity"
},
"Action": "sts:AssumeRole"
}
]
}
'@
`$role = New-IAMRole -RoleName "`$roleName" -AssumeRolePolicyDocument `$policy
}
else
{
`$policy = @'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "`$entity.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
'@
`$role = New-IAMRole -RoleName "`$roleName" -AssumeRolePolicyDocument `$policy
}
if(`$policyName -eq "managed")
{
`$file = Invoke-WebRequest (Get-S3PreSignedURL -BucketName $($bucket.BucketName) -Expire (Get-Date).AddMinutes(1) -Protocol HTTP -Key "`$entity/`$roleName/`$policyName.json")
`$json = [System.Text.Encoding]::ASCII.GetString(`$file.content)
`$jsonObject = ConvertFrom-Json `$json
foreach(`$arn in `$jsonObject.arn)
{
Register-IAMRolePolicy -RoleName "`$roleName" -PolicyArn "`$arn"
}
}
else
{
`$file = Invoke-WebRequest (Get-S3PreSignedURL -BucketName $($bucket.BucketName) -Expire (Get-Date).AddMinutes(1) -Protocol HTTP -Key "`$entity/`$roleName/`$policyName.json")
`$json = [System.Text.Encoding]::ASCII.GetString(`$file.content)
Write-IAMRolePolicy -RoleName "`$roleName" -PolicyDocument `$json -PolicyName "`$policyName"
}
}
"@
Add-Content C:\FUNCTION-RoleManager-1\FUNCTION-RoleManager-1.ps1 -Value $function
Publish-AWSPowerShellLambda -ScriptPath C:\FUNCTION-RoleManager-1\FUNCTION-RoleManager-1.ps1 -Name FUNCTION-RoleManager-1 -Region us-west-2 -IAMRoleArn $role.Arn
# Configure the Trigger
$lambda = Get-LMFunctionList|Where-Object{$_.Role -eq $role.Arn}
$rule = Write-CWERule -Name "RULE-CronHourly" -ScheduleExpression "rate(1 hour)" -State ENABLED
$target = New-Object Amazon.CloudWatchEvents.Model.Target
$target.Arn = $lambda.FunctionArn
$target.Id = $lambda.RevisionId
Write-CWETarget -Rule $rule.Substring($rule.IndexOf("/")+1) -Target $target
# Create a Test Role
$policy = @"
{
"arn": [
"arn:aws:iam::aws:policy/AdministratorAccess"
]
}
"@
Write-S3Object -BucketName $bucket.BucketName -Key "$((Get-STSCallerIdentity).Account)/ROLE-Name/managed.json" -Content $policy
$policy = @"
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
]
}
"@
Write-S3Object -BucketName $bucket.BucketName -Key "$((Get-STSCallerIdentity).Account)/ROLE-Name/inline/POLICY-FullAdmin.json" -Content $policy
# Test the Function
Invoke-LMFunction -FunctionName $lambda.FunctionName
Get-IAMRole -RoleName "ROLE-Name"
Loading