Created
October 9, 2014 05:09
-
-
Save jschell/28d3c76a98124c2d1015 to your computer and use it in GitHub Desktop.
misc ps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .SYNOPSIS | |
| Script is using Miscrosoft-Windows-Backup Event log and windows.ServerBackup snapin to get informations of last backup. | |
| There is option to perform backup and test recovery from selected backupfile. | |
| .DESCRIPTION | |
| Script is using Miscrosoft-Windows-Backup Event log and windows.ServerBackup snapin to get informations of last backup. | |
| There is an option to perform a backup and test recovery from selected backupfile. | |
| Script is using XML for backup config. XML has to have same name as machines hostname an has to be stored in same location as script. | |
| This script requires Windows Server Backup Feature and .NET 3.5 installed on machine. | |
| Working on Windows Server 2008 R2, Windows Server 2012, Windows Server 2012 R2. Should work on Windows 8 and Windows 8.1. | |
| Not working on Windows 7 since there is no windows.ServerBackup PS Snappin. | |
| .PARAMETER -Xml | |
| Tell script not to use default XML file but another one. Use full path. | |
| .PARAMETER -BkpNo | |
| What number of backup to show. | |
| For example: "-BkpNo 1" will show results for the last backup. "-BkpNo 2" win show results for one before the last backup. Default is: 0. | |
| .PARAMETER -Restore | |
| Performs restore of selected backup. Default is last backup. backup is selected by adding number of previous backup. | |
| For example: "-Restore 1" will restore last backup. "-Restore 2" will restore one before the last backup. | |
| .PARAMETER -NoMail | |
| Option to keep silent if errors. No mail will be sent. | |
| .PARAMETER -Backup | |
| When prameter -Backup is used script perform backup job with selected options. See parameters BkpServer, BkpSource, BkpTargetFolder. | |
| .PARAMETER -BkpSource | |
| Define drive letter to be backed up. Multiple sources separated by a comma. When this parameter is not used script will backup all volumes on server. Overrides XML configuration! | |
| .PARAMETER -BkpDest | |
| Define path to Backup server (BkpServer) where to store backup. Overrides XML configuration! | |
| .EXAMPLE | |
| .\GetLastBackupStatus.ps1 -Backup | |
| This Example will perform backup job with options configured in XML file and shows its results on the screen. Also will send email if backup fails or generates any other errors or warnings. | |
| .EXAMPLE | |
| .\GetLastBackupStatus.ps1 -Restore 0 -NoMail -Hours 72 -Backup -BkpSource C:,D: -BkpDest \\SRVBKP01\Backup | |
| This Example overrides XML settings and will check for last backup in 72 hours and write output only on screen. It will perform backup of C:, D:, SystemState and bare Metal recovery to destination \\SRVBKP01\Backup\SERVERNAME\. It will also try restore from last backup file. | |
| .link | |
| https://gallery.technet.microsoft.com/scriptcenter/Windows-backup-script-with-475aab8f | |
| #> | |
| #Set all parameters | |
| Param( | |
| [Int]$Hours = 72, | |
| [Switch]$Restore = $false, | |
| [Parameter(Position=0)] | |
| [Int]$BkpNo, | |
| [Switch]$NoMail = $false, | |
| [Switch]$Mail = $false, | |
| [Switch]$Backup = $false, | |
| [String]$BkpServer, | |
| [Array]$BkpSource = $null, | |
| [String]$BkpDest = $null, | |
| [String]$xml = $null | |
| ) | |
| #Add Snapins | |
| #check if console is running in elevated mode | |
| $winid=[System.Security.Principal.WindowsIdentity]::GetCurrent() | |
| $winprin=new-object System.Security.Principal.WindowsPrincipal($winid) | |
| $adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator | |
| $isadmin=$winprin.IsInRole($adm) | |
| if (!$isadmin) { | |
| Write-Host "You're NOT in an elevated session." -ForegroundColor Red | |
| Break | |
| } | |
| else { | |
| Write-Host "You're in an elevated session. Let's continue." -ForegroundColor DarkGreen | |
| } | |
| #get Windows version | |
| $WinVersionMaj = [System.Environment]::OSVersion.Version.Major | |
| $WinVersionMin = [System.Environment]::OSVersion.Version.Minor | |
| $WinVersion = "$WinVersionMaj$WinVersionMin" | |
| $PSVersionMaj = $PSVersionTable.PSVersion.Major | |
| $PSVersionMin = $PSVersionTable.PSVersion.Minor | |
| if($PSVersionMaj -lt '3'){ | |
| Write-Host 'This script requires at least Powershell version 3.0. Please upgrade Powershell before running script.' | |
| } | |
| if($WinVersion -lt '62'){ | |
| $BKPFeatureStatus = (Get-WindowsFeature | Where {$_.Name -eq 'Backup'}).Installstate | |
| $BKPFeatureToolsStatus = (Get-WindowsFeature | Where {$_.Name -eq 'Backup-Tools'}).Installstate | |
| $DotNETFeatureStatus = (Get-WindowsFeature | Where {$_.Name -eq 'NET-Framework-Core'}).Installstate | |
| if(($BKPFeatureStatus -ne 'Installed') -or ($BKPFeatureToolsStatus -ne 'Installed')){ | |
| Add-WindowsFeature -Name 'Backup-Features' -IncludeAllSubFeature | Out-Null | |
| if ((Get-PSSnapin -Name windows.ServerBackup -ErrorAction SilentlyContinue) -eq $null){ | |
| Add-PSSnapin windows.ServerBackup -ErrorAction Stop | |
| } | |
| } | |
| if($DotNETFeatureStatus -ne 'Installed'){ | |
| Add-WindowsFeature -Name 'NET-Framework-Core' | Out-Null | |
| } | |
| }else{ | |
| $BKPFeatureStatus = (Get-WindowsFeature | Where {$_.Name -eq 'Windows-Server-Backup'}).Installstate | |
| $DotNETFeatureStatus = (Get-WindowsFeature | Where {$_.Name -eq 'NET-Framework-45-Core'}).Installstate | |
| if($BKPFeatureStatus -ne 'Installed'){ | |
| Add-WindowsFeature -Name 'Windows-Server-Backup' -IncludeAllSubFeature | Out-Null | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function check-Svc { | |
| <# | |
| .Notes | |
| Name: Gary L Jackson --Another Bad Idea | |
| Ver: 3.0 | |
| Date: 17-Feb-2014 | |
| Mod: 18-Feb-2014, --GLJ, Script will now only start jobs that are set to Autostart | |
| File: StartServicesV3.ps1 | |
| .SYNOPSIS | |
| This script is used to monitor services | |
| .DESCRIPTION | |
| This script is used to monitor services. The script will restart the service(s) three times with the third | |
| time also generating an email message to a list of users. The script will also insure that the service(s) is | |
| set to Autostart. The script can be ran as a scheduled task. | |
| .EXAMPLE | |
| StartServicesV3.ps1 | |
| .Link | |
| https://gallery.technet.microsoft.com/scriptcenter/Use-PowerShell-to-monitor-0c1974a9 | |
| #> | |
| function mailit($subj,$msg) { | |
| $EmailList="johndoe@acme.com | |
| $MailMessage= @{ | |
| To=$EmailList | |
| From="DONOTREPLY@acme.com" | |
| Subject=$subj | |
| Body=$msg | |
| SmtpServer="smtp.acme.com" | |
| ErrorAction="SilentlyContinue" | |
| } | |
| Send-MailMessage @MailMessage | |
| } | |
| function start-Svc($svc,$computer) { | |
| [CmdletBinding()] | |
| $tempDir="c:\temp" | |
| if (!(Test-Path $tempDir)) { | |
| try { | |
| $null=New-Item $tempDir -ItemType directory -Force -ErrorAction Stop -ErrorVariable DirectoryError | |
| } | |
| Catch { | |
| write-Error "An error occurred created the archive folder $tempDir. Error: $DirectoryError" | |
| } | |
| } | |
| $UniqueName="$computer" + "$svc" | |
| $counterFile="c:\temp\counter$UniqueName.txt" | |
| if (!(Test-Path $counterFile)) { | |
| try { | |
| $null=New-Item $counterFile -ItemType file -Force -ErrorAction Stop -ErrorVariable FileError | |
| } | |
| Catch { | |
| Write-Warning "An error occurred creating the file $counterFile. Error: $FileError" | |
| } | |
| } | |
| if ((Get-ChildItem $counterFile).length -eq 0) { | |
| Write-Output 1 > $counterFile | |
| } | |
| [int]$counter=Get-Content $counterFile | |
| if ($counter -gt 2) { | |
| $Subj="***Restarting $svc service" | |
| $msg="Service $svc has stopped $counter times. Restarting..." | |
| try { | |
| get-Service -Name $svc -ComputerName $computer| set-service -StartupType Automatic -ErrorAction Stop | |
| get-Service -Name $svc -ComputerName $computer| set-service -Status Running -ErrorAction Stop | |
| mailit $subj $msg | |
| } | |
| Catch { | |
| $ErrorMessage=$_.Exception.Message | |
| $FailedItem=$_.Exception.ItemName | |
| } | |
| Write-Output 1 > $counterFile | |
| } | |
| else { | |
| $counter=$counter+1 | |
| Write-Output $counter > $counterFile | |
| try { | |
| get-Service -Name $svc -ComputerName $computer| set-service -StartupType Automatic -ErrorAction Stop | |
| get-Service -Name $svc -ComputerName $computer| set-service -Status Running -ErrorAction Stop | |
| } | |
| Catch { | |
| $ErrorMessage=$_.Exception.Message | |
| $FailedItem=$_.Exception.ItemName | |
| } | |
| } | |
| } | |
| $servicesToMonitor="Spooler","SNMPTRAP" | |
| $computer="ACMETSTSERVER" | |
| foreach ($serviceToMonitor in $servicesToMonitor) { | |
| $Stopped=(Get-WmiObject win32_service -filter "Name='$serviceToMonitor' AND startmode='auto' AND state<>'Running'" -ComputerName $computer).State | |
| if ($Stopped) { | |
| start-Svc $serviceToMonitor $computer | |
| } | |
| } | |
| } | |
| check-Svc |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Requires -Module ActiveDirectory | |
| <# | |
| .SYNOPSIS | |
| This script retrieves the ACL from an Active Directory-integrated DNS record | |
| .NOTES | |
| Created on: 8/5/2014 | |
| Created by: Adam Bertram | |
| Filename: Get-AdDnsRecordAcl.ps1 | |
| .EXAMPLE | |
| PS> .\Get-AdDnsRecordAcl.ps1 -Hostname 'SERVER1' | |
| This example retrieves the ACL for the hostname SERVER1 inside the current forest-integrated | |
| DNS zone inside Active Directory | |
| .EXAMPLE | |
| PS> .\Get-AdDnsRecordAcl.ps1 -Hostname 'SERVER1' -AdDnsIntegration 'Domain' | |
| This example retrieves the ACL for the hostname SERVER1 inside the current domain-integrated | |
| DNS zone inside Active Directory | |
| .PARAMETER Hostname | |
| The hostname for the DNS record you'd like to see | |
| .PARAMETER DomainName | |
| The Active Directory domain name. This defaults to the current domain | |
| .PARAMETER | |
| This is the DNS integration type. This can either be Forest and Domain. | |
| .Link | |
| http://www.adamtheautomator.com/get-active-directory-dns-record-acl/ | |
| #> | |
| [CmdletBinding()] | |
| [OutputType('System.DirectoryServices.ActiveDirectorySecurity')] | |
| param ( | |
| [Parameter(Mandatory, | |
| ValueFromPipeline, | |
| ValueFromPipelineByPropertyName)] | |
| [string[]]$Hostname, | |
| [Parameter(ValueFromPipeline, | |
| ValueFromPipelineByPropertyName)] | |
| [string]$DomainName = (Get-ADDomain).Forest, | |
| [ValidateSet('Forest','Domain')] | |
| [Parameter(ValueFromPipeline, | |
| ValueFromPipelineByPropertyName)] | |
| [string[]]$AdDnsIntegration = 'Forest' | |
| ) | |
| begin { | |
| $ErrorActionPreference = 'Stop' | |
| Set-StrictMode -Version Latest | |
| } | |
| process { | |
| try { | |
| $Path = "AD:\DC=$DomainName,CN=MicrosoftDNS,DC=$AdDnsIntegration`DnsZones,DC=$($DomainName.Split('.') -join ',DC=')" | |
| foreach ($Record in (Get-ChildItem -Path $Path)) { | |
| if ($Hostname -contains $Record.Name) { | |
| Get-Acl -Path "ActiveDirectory:://RootDSE/$($Record.DistinguishedName)" | |
| } | |
| } | |
| } catch { | |
| Write-Error $_.Exception.Message | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #link https://github.com/desek/public | |
| function Get-AzurePowershellModule | |
| { | |
| [cmdletbinding()] | |
| Param( | |
| [switch]$ShowVersion, | |
| [switch]$Install, | |
| [string]$Path=$null | |
| ) | |
| BEGIN | |
| { | |
| If ($ShowVersion.IsPresent) | |
| { | |
| $Modules = Get-Module -ListAvailable | |
| $InstalledVersion = ($Modules | Where-Object {$_.Name -eq "Azure"}).Version.ToString() | |
| Write-Output "Installed: $InstalledVersion" | |
| } | |
| } | |
| PROCESS { | |
| Try | |
| { | |
| $WebSite = Invoke-WebRequest -Uri "https://github.com/Azure/azure-sdk-tools/releases/latest" -Method Get -TimeoutSec 30 | |
| } | |
| Catch | |
| { | |
| Throw "Failed to get Web Content for Azure Powershell Module: $($_.Exception.Message)" | |
| } | |
| if ($ShowVersion.IsPresent) | |
| { | |
| $LatestVersion = ($WebSite.Links | Where-Object {$_.href -eq $WebSite.BaseResponse.ResponseUri.AbsolutePath}).innerText | |
| Write-Verbose "LatestVersion = $LatestVersion" | |
| Write-Output "Latest: $LatestVersion" | |
| } | |
| $DownloadURL = ($WebSite.Links | Where-Object {$_.InnerHTML -eq "Windows Standalone"}).href | |
| Write-Verbose "DownloadURL = $DownloadURL" | |
| If ($Path -ne $null) | |
| { | |
| if ((Test-Path $Path) -eq $false) | |
| { | |
| $OutFilePathRoot = (Get-Item $Path).Directory | |
| } | |
| } | |
| if ($OutFilePathRoot -eq $null) | |
| { | |
| $OutFilePathRoot = $env:TEMP | |
| } | |
| $OutFilePath = "$($OutFilePathRoot)\$($DownloadURL.Split("/")[-1])" | |
| Write-Verbose "OutFilePath = $($OutFilePath)" | |
| Invoke-WebRequest -Uri $DownloadURL -OutFile $OutFilePath -Method Get -TimeoutSec 60 | |
| $LogPath = $OutFilePath.Split(".") | |
| $LogPath[-1] = "log" | |
| $LogPath = $LogPath -join "." | |
| Write-Verbose "LogPath = $($LogPath)" | |
| If ($Install.IsPresent) | |
| { | |
| Start-Process $OutFilePath -ArgumentList "/quiet /norestart /log $($LogPath)" -Wait -PassThru | |
| } | |
| else | |
| { | |
| Write-Output "Azure Powershell Module downloaded to: $($OutFilePath)" | |
| } | |
| } | |
| END | |
| { | |
| If ($Install.IsPresent) | |
| { | |
| Remove-Item -Path $OutFilePath -Force -Verbose | |
| } | |
| } | |
| } | |
| #Get-AzurePowershellModule -Install -Verbose |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## link: https://gallery.technet.microsoft.com/scriptcenter/Get-Missing-Updates-with-ab80bf4e | |
| function Get-MissingUpdates { | |
| [CmdletBinding()] | |
| [OutputType([System.Management.Automation.PSCustomObject])] | |
| param ( | |
| [Parameter(Mandatory, | |
| ValueFromPipeline, | |
| ValueFromPipelineByPropertyName)] | |
| [string]$ComputerName | |
| ) | |
| begin { | |
| function Get-32BitProgramFilesPath { | |
| if ((Get-Architecture) -eq 'x64') { | |
| ${ env:ProgramFiles(x86) } | |
| } else { | |
| $env:ProgramFiles | |
| } | |
| } | |
| function Get-Architecture { | |
| if ([System.Environment]::Is64BitOperatingSystem) { | |
| 'x64' | |
| } else { | |
| 'x86' | |
| } | |
| } | |
| $Output = @{ } | |
| } | |
| process { | |
| try { | |
| ## Remove any previous reports | |
| Get-ChildItem "$($Env:USERPROFILE)\SecurityScans\*" -Recurse -ea 'SilentlyContinue' | Remove-Item -Force -Recurse | |
| ## Run the report to create the output XML | |
| $ExeFilePath = "$(Get-32BitProgramFilesPath)\Microsoft Baseline Security Analyzer 2\mbsacli.exe" | |
| if (!(Test-Path $ExeFilePath)) { | |
| throw "$ExeFilePath not found" | |
| } | |
| & $ExeFilePath /target $ComputerName /wi /nvc /o %C% 2>&1> $null | |
| ## Convert the report to XML so I can use it | |
| [xml]$ScanResults = Get-Content "$($Env:USERPROFILE)\SecurityScans\$($Computername.Split('.')[0]).mbsa" | |
| $UpdateSeverityLabels = @{ | |
| '0' = 'Other' | |
| '1' = 'Low' | |
| '2' = 'Moderate' | |
| '3' = 'Important' | |
| '4' = 'Critical' | |
| } | |
| $MissingUpdates = $ScanResults.SelectNodes("//Check[@Name='Windows Security Updates']/Detail/UpdateData[@IsInstalled='false']") | |
| foreach ($Update in $MissingUpdates) { | |
| $Ht = @{ } | |
| $Properties = $Update | Get-Member -Type Property | |
| foreach ($Prop in $Properties) { | |
| $Value = ($Update | select -expandproperty $Prop.Name) | |
| if ($Prop.Name -eq 'Severity') { | |
| $Value = $UpdateSeverityLabels[$Value] | |
| } | |
| $Ht[$Prop.Name] = $Value | |
| } | |
| [pscustomobject]$Ht | |
| } | |
| } catch { | |
| Write-Error "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function move-log { | |
| <# | |
| .NOTES | |
| Name: Gary L Jackson --Another Bad Idea | |
| Ver: 5.0 | |
| Date: 04-Nov-2013 | |
| Mod: 05-Nov-2013, --GLJ, Changed folder structure to YYYY-MM. | |
| 05-Nov-2013, --GLJ, Added folder compression | |
| 06-Nov-2013, --GLJ, Noticed that some files were not being compressed in the compressed folders. | |
| Added file compression to force the issue | |
| 07-Nov-2013, --GLJ, Unable to compress files via UNC path. Added drive mapping to the BEGIN section | |
| as a workaround. The share will be mapped to the X-drive | |
| .SYNOPSIS | |
| Move specified log files to an archive directory | |
| .DESCRIPTION | |
| This script will move specified log files that are 30 days old or older from X:\Test\* to an archive directory. | |
| The file will be moved to a subdirectory based on the Month and year of the last write time for that file. If the folder does not exist, it | |
| will be created. Both the folders AND the files will be compressed | |
| .PARAMETER LogPath | |
| Specifies the root folder of the log files | |
| Default=c:\folder1\logFileFolder | |
| .PARAMETER DaysBack | |
| Specifies how old, in days, of the log files to be moved. | |
| Default=30 | |
| .EXAMPLE | |
| move-log | |
| The command above will move all log files from X:\Test\* to the appropriate subfolder for the month. | |
| .EXAMPLE | |
| move-log -daysBack '3' | |
| The command above will move all log files older than 3 days from X:\Test\* to the appropriate subfolder on X:\Test\"MonthYear". | |
| .link | |
| https://gallery.technet.microsoft.com/scriptcenter/Move-log-files-to-an-84b99468 | |
| #> | |
| [CmdletBinding()] | |
| Param | |
| ( | |
| Parameter(Mandatory=$false)][ValidateScript({ Test-Path $_ -PathType Container })] | |
| [string]$LogPath="X:\", | |
| [Parameter(Mandatory=$false)][int]$daysBack="30" | |
| ) | |
| Begin | |
| { | |
| remove-psdrive -name X -force -ErrorAction SilentlyContinue | |
| New-PSDrive -name X -Root \\acmeserver\logFileFolder -Persist -PSProvider FileSystem | |
| $ArchiveFolder="X:\" | |
| } | |
| Process | |
| { | |
| function compress-files ($FileToCompress) { | |
| Write-Verbose "Starting file compression" | |
| $CompressIt=Get-WmiObject -query "Select * from CIM_DataFIle Where Name='$FileToCompress'" | |
| $CompressIt.Compress() | |
| } | |
| Write-Verbose "Starting the process block" | |
| $RefDate=(Get-Date).AddDays(-$daysBack) | |
| $oldFiles=Get-ChildItem -filter * -Path $LogPath | where {$_.LastWriteTime -lt "$RefDate"} | |
| foreach ($oldFile in $oldFiles) { | |
| $subFolder=(Get-Date $oldFile.LastWriteTime -Format yyyy-MM) | |
| if (!(Test-Path $subFolder)) { | |
| Write-Verbose "The subfolder $subFolder does not exist. It will be created now" | |
| try { | |
| $null=New-Item $ArchiveFolder$subFolder -ItemType directory -Force -ErrorAction Stop -ErrorVariable DirectoryError | |
| Write-Verbose "COmpressing the folder" | |
| Invoke-WmiMethod -Path "Win32_Directory.Name='$ArchiveFolder$subFolder'" -Name compress | |
| } | |
| Catch { | |
| write-Error "An error occurred created the archive folder $ArchiveFolder$subFolder. Error: $DirectoryError" | |
| } | |
| } | |
| try | |
| { | |
| Write-Verbose "Moving old files to the archive folders" | |
| Move-Item "$($oldFile.DirectoryName)\$oldFile" $ArchiveFolder$subFolder -Force -ea stop -ErrorVariable MoveError | |
| $FileToCompress="$ArchiveFolder$subFolder\$oldFile" | |
| $FileToCompress=$FileToCompress.Replace("\","\\") | |
| compress-files $FileToCompress | |
| } | |
| Catch | |
| { | |
| Write-Error "Error moving file $oldfile to destination $ArchiveFolder$subFolder. Error: $MoveError" | |
| } | |
| } | |
| } | |
| End | |
| { | |
| } | |
| } | |
| move-log | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Set-AdminUser { | |
| <# | |
| .SYNOPSIS | |
| Clears adminCount, and enables inherited security on a user account. | |
| .DESCRIPTION | |
| Clears adminCount, and enables inherited security on a user account. | |
| .NOTES | |
| Version : v1.0 | |
| Wish list : | |
| Rights Required : UserAdministrator | |
| Sched Task Req'd : No | |
| Lync Version : N/A | |
| Lync Version : N/A | |
| Author : Pat Richard, Exchange MVP | |
| Email/Blog/Twitter : pat@innervation.com http://www.ehloworld.com @patrichard | |
| Dedicated Post : http://www.ehloworld.com/1621 | |
| Disclaimer : You running this script means you won't blame me if this breaks your stuff. | |
| Info Stolen from : http://serverfault.com/questions/304627/powershell-script-to-find-ad-users-with-admincount-0 | |
| : http://morgansimonsen.wordpress.com/2012/01/26/adminsdholder-protected-groups-sdprop-and-moving-mailboxes-in-exchange/ | |
| .LINK | |
| http://www.ehloworld.com/1621 | |
| .INPUTS | |
| You can pipeline input to this command | |
| .PARAMETER UserName | |
| Create the scheduled task to run the script daily. It does NOT create the required Exchange receive connector. | |
| .EXAMPLE | |
| Set-AdminUser -UserName [user name] | |
| Description | |
| ----------- | |
| Clears the adminCount of the specified user, and enabled inherited security | |
| .EXAMPLE | |
| Get-AdGroupMember [group name] | Set-AdminUser | |
| Description | |
| ----------- | |
| Clears the adminCount of all group members, and enabled inherited security | |
| #> | |
| #Requires -Version 2.0 | |
| [CmdletBinding(SupportsShouldProcess = $True)] | |
| param ( | |
| [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $True, Mandatory = $False)] | |
| [ValidateNotNullOrEmpty()] | |
| [string]$UserName | |
| ) | |
| Begin{ | |
| ## allows inheritance | |
| [bool]$isProtected = $false | |
| ## preserves inherited rules | |
| [bool]$PreserveInheritance = $true | |
| } | |
| Process{ | |
| [string]$dn = (Get-ADUser $UserName).DistinguishedName | |
| Set-AdObject -identity $dn -clear adminCount | |
| $user = [ADSI]"LDAP://$dn" | |
| $acl = $user.objectSecurity | |
| Write-Verbose $dn | |
| Write-Verbose "Original permissions blocked:" | |
| Write-Verbose $acl.AreAccessRulesProtected | |
| if ($acl.AreAccessRulesProtected){ | |
| $acl.SetAccessRuleProtection($isProtected,$PreserveInheritance) | |
| $inherited = $acl.AreAccessRulesProtected | |
| $user.commitchanges() | |
| Write-Verbose "Updated permissions blocked:" | |
| Write-Verbose $acl.AreAccessRulesProtected | |
| } | |
| } | |
| End{ | |
| remove-variable acl | |
| remove-variable UserName | |
| remove-variable isProtected | |
| remove-variable PreserveInheritance | |
| remove-variable dn | |
| remove-variable user | |
| } | |
| } # end function Set-AdminUser |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Checks whether a user is a member of a high privileged group | |
| .DESCRIPTION | |
| Checks whether the supplied user object is a member of any of the following high privileged groups: | |
| - Account Operators | |
| - BUILTIN\Administrators | |
| - Backup Operators | |
| - Domain Admins | |
| - Enterprise Admins | |
| - Print Operators | |
| - Schema Admins | |
| - Server Operators | |
| .EXAMPLE | |
| Get-ADUser -Identity ianfarr | Test-ADUserHighPrivilegeGroupMembership | |
| Gets the AD user with the SamAccountName ianfarr and pipes it into the Test-ADUserHighPrivilege | |
| function which lists any high privilege group memberships. | |
| .EXAMPLE | |
| Test-ADUserHighPrivilegeGroupMembership -User "CN=Ian Farr,OU=User Accounts,DC=contoso,DC=com" | |
| Uses the distinguished name for the user IanFarr to list any high privilege group memberships. | |
| .NOTES | |
| THIS CODE-SAMPLE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED | |
| OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR | |
| FITNESS FOR A PARTICULAR PURPOSE. | |
| This sample is not supported under any Microsoft standard support program or service. | |
| The script is provided AS IS without warranty of any kind. Microsoft further disclaims all | |
| implied warranties including, without limitation, any implied warranties of merchantability | |
| or of fitness for a particular purpose. The entire risk arising out of the use or performance | |
| of the sample and documentation remains with you. In no event shall Microsoft, its authors, | |
| or anyone else involved in the creation, production, or delivery of the script be liable for | |
| any damages whatsoever (including, without limitation, damages for loss of business profits, | |
| business interruption, loss of business information, or other pecuniary loss) arising out of | |
| the use of or inability to use the sample or documentation, even if Microsoft has been advised | |
| of the possibility of such damages, rising out of the use of or inability to use the sample script, | |
| even if Microsoft has been advised of the possibility of such damages. | |
| .link | |
| https://gallery.technet.microsoft.com/scriptcenter/Test-ADUserHighPrivilegeGro-7660b3a4 | |
| #> | |
| ########################################################################################################## | |
| #Requires -version 3 | |
| #Requires -modules ActiveDirectory | |
| Function Test-ADUserHighPrivilegeGroupMembership { | |
| #Define and validate parameters | |
| [CmdletBinding()] | |
| Param( | |
| #The target user account | |
| [parameter(Mandatory,Position=1,ValueFromPipeline)] | |
| [ValidateScript({Get-ADUser -Identity $_})] | |
| $User | |
| ) | |
| #Process each value supplied by the pipeline | |
| Process { | |
| #Ensures all variables are empty | |
| $Groups = $Null | |
| $Privs = $Null | |
| #Use the MemberOf atttibute to retrieve a list of groups | |
| $Groups = (Get-ADUser -Identity $User -Property MemberOf).MemberOf | |
| #Evaluate each entry | |
| Switch -Wildcard ($Groups) { | |
| #Search for membership of Account Operators | |
| "CN=Account Operators,CN=BuiltIn*" { | |
| #Capture membership in a custom object and add to an array | |
| [Array]$Privs += [PSCustomObject]@{ | |
| User = $User | |
| MemberOf =$Switch.Current | |
| } #End of $Privs | |
| } #End of "CN=Account Operators,CN=BuiltIn*" | |
| #Search for membership of Administrators | |
| "CN=Administrators,CN=BuiltIn*" { | |
| #Capture membership in a custom object and add to an array | |
| [Array]$Privs += [PSCustomObject]@{ | |
| User = $User | |
| MemberOf =$Switch.Current | |
| } #End of $Privs | |
| } #End of "CN=Administrators,CN=BuiltIn*" | |
| #Search for membership of Backup Operators | |
| "CN=Backup Operators,CN=BuiltIn*" { | |
| #Capture membership in a custom object and add to an array | |
| [Array]$Privs += [PSCustomObject]@{ | |
| User = $User | |
| MemberOf =$Switch.Current | |
| } #End of $Privs | |
| } #End of "CN=Backup Operators,CN=BuiltIn*" | |
| #Search for membership of Domain Admins | |
| "CN=Domain Admins,CN=Users*" { | |
| #Capture membership in a custom object and add to an array | |
| [Array]$Privs += [PSCustomObject]@{ | |
| User = $User | |
| MemberOf =$Switch.Current | |
| } #End of $Privs | |
| } #End of "CN=Domain Admins,CN=Users*" | |
| #Search for membership of Enterprise Admins | |
| "CN=Enterprise Admins,CN=Users*" { | |
| #Capture membership in a custom object and add to an array | |
| [Array]$Privs += [PSCustomObject]@{ | |
| User = $User | |
| MemberOf =$Switch.Current | |
| } #End of $Privs | |
| } #End of "CN=Enterprise Admins,CN=Users*" | |
| #Search for membership of | |
| "CN=Print Operators,CN=BuiltIn*" { | |
| #Capture membership in a custom object and add to an array | |
| [Array]$Privs += [PSCustomObject]@{ | |
| User = $User | |
| MemberOf =$Switch.Current | |
| } #End of $Privs | |
| } #End of "CN=Print Operators,CN=BuiltIn*" | |
| #Search for membership of Schema Admins | |
| "CN=Schema Admins,CN=Users*" { | |
| #Capture membership in a custom object and add to an array | |
| [Array]$Privs += [PSCustomObject]@{ | |
| User = $User | |
| MemberOf =$Switch.Current | |
| } #End of $Privs | |
| } #End of "CN=Schema Admins,CN=Users*" | |
| #Search for membership of Server Operators | |
| "CN=Server Operators,CN=BuiltIn*" { | |
| #Capture membership in a custom object and add to an array | |
| [Array]$Privs += [PSCustomObject]@{ | |
| User = $User | |
| MemberOf =$Switch.Current | |
| } #End of $Privs | |
| } #End of "CN=Server Operators,CN=BuiltIn*" | |
| } #End of Switch -Wildcard ($Groups) | |
| #Return any high privilege group memberships | |
| If ($Privs) { | |
| #Return the contents of $Privs | |
| $Privs | |
| } #End of If ($Privs) | |
| } #End of Process block | |
| } #End of Function Test-ADUserHighPrivilegeGroupMembership | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Test-Online { | |
| <# | |
| .SYNOPSIS | |
| Test for connection status for one or more computers | |
| .DESCRIPTION | |
| Tests one or more computers for network connection. Two NoteProperties are added to the object(s) on their way through the pipeline: | |
| * OnlineStatus - will be $true if the computer is online, $false otherwise | |
| * IPV4Address - the IP address of the computer, if any | |
| Note this Cmdlet uses parallel processing techniques to test many computers at once, so results are returned very quickly, even for a large number of input objects. | |
| .PARAMETER Property | |
| The name of a property of InputObject that contains the name of the computer; required if InputObject is anything other than a string. | |
| .PARAMETER InputObject | |
| One or more objects to test for network connection | |
| .EXAMPLE | |
| 'Computer1','Computer2' | Test-Online -Property Name | ? OnlineStatus -eq $true | |
| .link | |
| https://gallery.technet.microsoft.com/scriptcenter/PowerShell-function-to-044d51a5 | |
| Tests 2 computers (named Computer1 and Computer2) and sends the names of those that are on the network down the pipeline. | |
| .INPUTS | |
| PSObject or string. | |
| .OUTPUTS | |
| Same as input, with two additional properties appended | |
| .NOTES | |
| Author: Dale Thompson | |
| LastEdit: 09/24/14 | |
| #Requires -Version 2.0 | |
| #> | |
| [CmdletBinding(DefaultParameterSetName = 'ByString')] | |
| Param ( | |
| [Parameter(Mandatory,ValueFromPipeline)] $InputObject, | |
| [Parameter(ParameterSetName='NotString',Mandatory,Position=0)] | |
| [ValidateNotNullOrEmpty()] [string] $Property | |
| ) | |
| BEGIN { | |
| $Jobs = @{} | |
| $MaxJobs = 50 | |
| $ProcessJobs = { | |
| Start-Sleep -Milliseconds 200 | |
| $Keys = ($Jobs.Keys).Clone() | |
| foreach ($j in $Keys) { | |
| if ($Jobs[$j][0].State -eq 'Completed') { | |
| $Status = $false; $IPV4Address = '0.0.0.0' | |
| $Jobs[$j][0] | Receive-Job | ? StatusCode -eq 0 | Select-Object -First 1 | % { | |
| $Status = $true | |
| $Address = $_.IPV4Address | |
| if ($Address.PSObject.Properties['IPAddressToString']) { | |
| $IPV4Address = $Address.IPAddressToString | |
| } else { | |
| $IPV4Address = $_.Address | |
| } | |
| } | |
| $Jobs[$j][1] | Add-Member -Force -PassThru -NotePropertyMembers @{ | |
| OnlineStatus = $Status | |
| IPV4Address = $IPV4Address | |
| } | |
| try { Remove-Job $Jobs[$j][0]; $Jobs.Remove($j) } catch {} | |
| } | |
| } | |
| } | |
| } | |
| PROCESS { | |
| while ($Jobs.Count -gt $MaxJobs) { . $ProcessJobs } | |
| $CompName = switch ($PSCmdlet.ParameterSetName) { | |
| 'ByString' { $InputObject.ToString() } | |
| 'NotString' { $InputObject | Select-Object -Property $Property | % { $_.$Property } } | |
| } | |
| if ($CompName) { | |
| $Job = Test-Connection -Count 3 -ComputerName $CompName -AsJob -EA SilentlyContinue | |
| try { | |
| $Jobs.Add($CompName, @($Job,$InputObject)) | |
| } catch { | |
| Stop-Job $Job | |
| Remove-Job $Job | |
| } | |
| } else { | |
| $InputObject | Add-Member -Force -PassThru -NotePropertyMembers @{ | |
| OnlineStatus = $false | |
| IPV4Address = '0.0.0.0' | |
| } | |
| } | |
| } | |
| END { while ($Jobs.Count -gt 0) { . $ProcessJobs } } | |
| } # Test-Online |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment