├── Networking
├── README.md
├── SendTCPRequest.ps1
├── pinger.ps1
├── BadHorse.ps1
├── ConnectivityReport.ps1
├── PingSweepInvokeParallel.ps1
├── Find_Wireless_Adapters.ps1
├── PingSweep.ps1
├── CopyURL.ps1
├── RestartDNS.ps1
├── CurrentIP.ps1
├── LatencyTest.ps1
├── FindShares.ps1
├── AddDHCPReservations.ps1
└── Wifi.ps1
├── DSC
├── README.md
├── 7z1700-x64.msi
├── DSC Advanced Configuration Data Learning Path
│ ├── 08 - You Need a Pipeline.url
│ ├── 05 - The Datum Module.url
│ ├── 10 - One MOF to Rule them All.url
│ ├── 07 - DscInfraSample.url
│ ├── 04 - Making Sense of DSC Configuration Data.url
│ ├── 06 - An Opinionated DSC Solution, with Tooling.url
│ ├── 09 - The Release Pipeline Model.url
│ ├── 02 - Managing Advanced DSC Configurations and Configuration Data.url
│ ├── 01 - DSC Configuration Data Layout Tips and Tricks.url
│ └── 03 - The DSC Configuration Data Problem.url
├── Partial_Configs_Demo
│ ├── 2-First_Config.ps1
│ ├── 4-Deploy_Configs.ps1
│ ├── 3-Second_Config.ps1
│ └── 1-LCM_Partial_Config_Setup.ps1
├── FileServer.ps1
├── DisableScreenLock.ps1
├── BuildFeatureList.ps1
├── BuildAllNodesList.ps1
├── PackageResource.ps1
├── AutomaticVariables.ps1
├── GroupResource.ps1
├── ScriptResourceDemo.ps1
├── UserResource.ps1
└── DscCertDemo.ps1
├── Timer.ps1
├── donate.png
├── Encryptor.ps1
├── HelpSearch1.ps1
├── Read-Key.ps1
├── GetExpiringCertificates.ps1
├── PowerShell-Depot.code-workspace
├── GeneratePasswordOneLiner.ps1
├── ActiveDirectory
├── UpdateADPropertyFromCSV.ps1
├── DirectorySearcher.ps1
├── GetADAttributes.ps1
├── MoveComputers.ps1
├── OldUser.ps1
├── AdminOSReport.ps1
├── ADStuff.ps1
├── DisableUser.ps1
└── CompareUsers.ps1
├── GetWeatherAPI.ps1
├── FibonacciSequence.ps1
├── LockedUsers.ps1
├── getEmoji.ps1
├── EmailCode.ps1
├── GetColors2.ps1
├── DateStamp.ps1
├── ArrayListExample.ps1
├── DecimalToBinary.ps1
├── HelpSearch2.ps1
├── BeepingFun.ps1
├── ReadHost-Color.ps1
├── Countdown.ps1
├── EnumColors.ps1
├── ConsoleColors.ps1
├── GeneratePassword.ps1
├── README.md
├── QueryLiveEventLog.ps1
├── EventRegistrationExample.ps1
├── GetOctoCatWisdom.ps1
├── QuerySavedEventLog.ps1
├── SortProperty.ps1
├── GetGPOVersion.ps1
├── MonitorGroupChanges.ps1
├── ImportandUpdateCSV.ps1
├── Progress.ps1
├── CopyDirectoryToSystems.ps1
├── NewLocalUserFromSerialNumber.ps1
├── DetectUSB-Remove.ps1
├── GetChuck.ps1
├── ArchiveFiles.ps1
├── CustomPipelineProperty.ps1
├── MoveHomeFolders.ps1
├── Caesar.ps1
├── FinallyDemo.ps1
├── ImportHashFromCSV.ps1
├── ChangeText.ps1
├── Azure
├── Point2SiteWin10Cert.ps1
├── EnumerateResourceTypeNamesByProviderPath.ps1
├── Set_JIT_on_ResourceGroup.ps1
├── MapAzureFileShare.ps1
├── GetAllAzureVmExtensions.ps1
├── GetAzureVmExtensions.ps1
├── GetAzureImages.ps1
├── GetVMFamilySizesByLocation.ps1
├── GetVMSizesByLocation.ps1
└── AzurePowerShell.ps1
├── SkylakeCheck.ps1
├── RemoveArchiveAttribute.ps1
├── Switch-Regex.ps1
├── GetColor.ps1
├── GetHash.ps1
├── RegisterRepo.ps1
├── WindowsTerminalExamples.ps1
├── GetJava.ps1
├── MixLetters.ps1
├── SetRecordingReminder.ps1
├── StripSignature.ps1
├── ArrayListLoopingExample.ps1
├── EncodeFile.ps1
├── ConsoleTextColorCombos.ps1
├── ComparePPTHashes.ps1
├── Speak.ps1
├── AudibleNotification.ps1
├── GetUptime.ps1
├── GetWebSensor2.ps1
├── GuessTheNumber.ps1
├── UnlockGeneticCode.ps1
├── WeatherDemo.ps1
├── Set-Color.ps1
├── GetLetterFrequency.ps1
├── DiffieHelmanExchangeExample.ps1
├── PrivateWorkingSet.ps1
├── RenAdmin.ps1
├── LICENSE
├── GetCalendar.ps1
├── DicewarePassword.ps1
├── StartContinousPing.ps1
├── DetectUSB.ps1
├── GetQuote.ps1
├── DupeFiles.ps1
├── BirthdayParadoxExample.ps1
├── MenuExample.ps1
├── ErrorHandlingDemo.ps1
├── LogonNotification.ps1
├── RetrieveAppEvents.ps1
├── GeneticCode.ps1
├── HackerTypist.ps1
├── GetOSReleaseId.ps1
├── InputBox.ps1
├── GetPwnedPassword.ps1
├── GetFolderNTFS.ps1
├── DynamicParameterValidateSetExample.ps1
├── CompareDictionary.ps1
├── DeadMan.ps1
├── SetConsoleFont.ps1
├── SendTextMessage.ps1
├── MorseCode.ps1
└── ConvertToPGPWords.ps1
/Networking/README.md:
--------------------------------------------------------------------------------
1 | # Networking scripts
2 |
--------------------------------------------------------------------------------
/DSC/README.md:
--------------------------------------------------------------------------------
1 | # Desired State Configuration examples
2 |
--------------------------------------------------------------------------------
/Timer.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/HEAD/Timer.ps1
--------------------------------------------------------------------------------
/donate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/HEAD/donate.png
--------------------------------------------------------------------------------
/Encryptor.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/HEAD/Encryptor.ps1
--------------------------------------------------------------------------------
/HelpSearch1.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/HEAD/HelpSearch1.ps1
--------------------------------------------------------------------------------
/DSC/7z1700-x64.msi:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/HEAD/DSC/7z1700-x64.msi
--------------------------------------------------------------------------------
/Read-Key.ps1:
--------------------------------------------------------------------------------
1 | Function Read-Key{
2 | $rawui = $Host.UI.RawUI
3 | $rk = $rawui.ReadKey()
4 | $rk
5 | }
--------------------------------------------------------------------------------
/GetExpiringCertificates.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/HEAD/GetExpiringCertificates.ps1
--------------------------------------------------------------------------------
/PowerShell-Depot.code-workspace:
--------------------------------------------------------------------------------
1 | {
2 | "folders": [
3 | {
4 | "path": "."
5 | }
6 | ],
7 | "settings": {}
8 | }
--------------------------------------------------------------------------------
/Networking/SendTCPRequest.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/HEAD/Networking/SendTCPRequest.ps1
--------------------------------------------------------------------------------
/GeneratePasswordOneLiner.ps1:
--------------------------------------------------------------------------------
1 | 1..10 | %{(33..57),(65..90),(97..122) -split ' ' | %{[char][int]$_} | Get-Random | Write-Host -NoNewline}; "`n"
2 |
--------------------------------------------------------------------------------
/ActiveDirectory/UpdateADPropertyFromCSV.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/HEAD/ActiveDirectory/UpdateADPropertyFromCSV.ps1
--------------------------------------------------------------------------------
/GetWeatherAPI.ps1:
--------------------------------------------------------------------------------
1 | $lat = 39.624532
2 | $long = -105.013504
3 | $uri = "https://api.weather.gov/points/$lat,$long"
4 | $results = Invoke-RestMethod $uri
5 |
6 |
--------------------------------------------------------------------------------
/FibonacciSequence.ps1:
--------------------------------------------------------------------------------
1 | cls
2 | $a = 0
3 | $b = 1
4 | $c = 0
5 | While($a -lt 10000){
6 | $c = $a + $b
7 | Write-Host "$c " -NoNewline
8 | $b = $a
9 | $a = $c
10 | }
--------------------------------------------------------------------------------
/LockedUsers.ps1:
--------------------------------------------------------------------------------
1 | Function Global:Get-LockedUser{
2 | Import-Module ActiveDirectory
3 | Get-ADUser -filter * -Properties lockedOut|
4 | Where-Object {$_.lockedout -eq $true}
5 | }
--------------------------------------------------------------------------------
/getEmoji.ps1:
--------------------------------------------------------------------------------
1 | Function Get-Emoji {
2 | Param(
3 | $unicode
4 | )
5 | $unicode32 = [System.Convert]::ToInt32($unicode,16)
6 | [char]::ConvertFromUtf32($unicode32)
7 | }
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/08 - You Need a Pipeline.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://bit.ly/2GNGp4o
6 |
--------------------------------------------------------------------------------
/EmailCode.ps1:
--------------------------------------------------------------------------------
1 | write-host ((0..98)| %{if(($_+1)%3 -eq 0){[char][int]("115104097119110046115116117103097114116064102111099097108112111105110116108101097114110046099111109"[($_-2)..$_] -join "")}}) -separator ""
2 |
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/05 - The Datum Module.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://github.com/gaelcolas/Datum
6 |
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/10 - One MOF to Rule them All.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://youtu.be/76YH2Lw98Oo
6 |
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/07 - DscInfraSample.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://github.com/gaelcolas/DscInfraSample
6 |
--------------------------------------------------------------------------------
/GetColors2.ps1:
--------------------------------------------------------------------------------
1 | $colors = [enum]::GetNames([consolecolor])
2 | ForEach($fg in $colors){
3 | ForEach($bg in $colors){
4 | Write-Host "This is $fg on $bg" -ForegroundColor $fg -BackgroundColor $bg
5 | }
6 | }
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/04 - Making Sense of DSC Configuration Data.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://bit.ly/2t9nec5
6 |
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/06 - An Opinionated DSC Solution, with Tooling.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://bit.ly/2TzHvTA
6 |
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/09 - The Release Pipeline Model.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,2
3 | [InternetShortcut]
4 | IDList=
5 | URL=http://aka.ms/thereleasepipelinemodelpdf
6 |
--------------------------------------------------------------------------------
/DateStamp.ps1:
--------------------------------------------------------------------------------
1 | Function global:Date-Stamp()
2 | {
3 | Write-Host -ForegroundColor "Red" $i `t (Get-Date)
4 | $global:i++
5 | if(!(Read-Host -prompt "Enter to Continue, any other key to cancel")){
6 | Date-Stamp
7 | }
8 | }
--------------------------------------------------------------------------------
/ArrayListExample.ps1:
--------------------------------------------------------------------------------
1 | $a = New-Object System.Collections.ArrayList
2 | $a.add("one")
3 | $a.add("two")
4 | $a.add("three")
5 | $a
6 | $a.insert(3,"four")
7 | $a.insert(2,"purple")
8 | $a
9 | $a.remove("purple")
10 | $a.removeat(2)
11 | $a
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/02 - Managing Advanced DSC Configurations and Configuration Data.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://bit.ly/2DzciJo
6 |
--------------------------------------------------------------------------------
/Networking/pinger.ps1:
--------------------------------------------------------------------------------
1 | For ($i = 1; $i -lt 255; ++$i){
2 | If(Test-Connection "192.168.0.$i" -Count 1 -Quiet){
3 | Write-Host -ForegroundColor Green "192.168.0.$i"
4 | }
5 | Else{
6 | Write-Host -ForegroundColor Red "192.168.0.$i"
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/01 - DSC Configuration Data Layout Tips and Tricks.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://www.petri.com/dsc-configuration-data-layout-tips-tricks
6 |
--------------------------------------------------------------------------------
/DSC/DSC Advanced Configuration Data Learning Path/03 - The DSC Configuration Data Problem.url:
--------------------------------------------------------------------------------
1 | [{000214A0-0000-0000-C000-000000000046}]
2 | Prop3=19,11
3 | [InternetShortcut]
4 | IDList=
5 | URL=https://gaelcolas.com/2018/01/29/the-dsc-configuration-data-problem/#more-1350
6 |
--------------------------------------------------------------------------------
/DecimalToBinary.ps1:
--------------------------------------------------------------------------------
1 | $number = 224
2 | $decimal = $number
3 | $binary = @()
4 | Do{
5 | $binary += ($decimal % 2)
6 | $decimal /=2
7 | $decimal = [Math]::Floor($decimal)
8 | } While ($decimal -ge 1)
9 | [array]::Reverse($binary)
10 | "Binary for $number is $binary"
--------------------------------------------------------------------------------
/HelpSearch2.ps1:
--------------------------------------------------------------------------------
1 | cls
2 | Set-Location $PSHOME\En-Us
3 | Get-Childitem about* |
4 | Select @{Label="FullName";Expression={$_.fullname}},
5 | @{Label="Text"; Expression={"$(cat $_.FullName)"}} |
6 | Select-String -inputobject $fullname "\bregex\b" -List | select fullname
--------------------------------------------------------------------------------
/BeepingFun.ps1:
--------------------------------------------------------------------------------
1 | $i = 0
2 | For($j = 1;$j -le 5;$j++){
3 | Do {
4 | $i = $i + 1000
5 | [console]::beep($i,200)
6 | } Until ($i -eq 10000)
7 | Do {
8 | $i = $i - 1000
9 | [console]::beep($i,200)
10 | } Until ($i -eq 1000)
11 | }
--------------------------------------------------------------------------------
/ReadHost-Color.ps1:
--------------------------------------------------------------------------------
1 | Function global:ReadHost-Color
2 | (
3 | [string]$prompt = "Next time, provide your own prompt",
4 | [string]$color = "yellow"
5 | )
6 | {
7 | [Console]::ForeGroundColor = $color
8 | Read-Host $prompt
9 | [Console]::ResetColor()
10 | }
--------------------------------------------------------------------------------
/Countdown.ps1:
--------------------------------------------------------------------------------
1 | Param (
2 | $startingPage = 1
3 | )
4 | For($i = $startingPage; $i -le 607;$i++){
5 | Write-Host "Page $i, pages remaining = $(607 - $i), percent remaining = $(100 - [math]::Round((($i / 607)*100),2))" -NoNewline -ForegroundColor DarkGray
6 | Read-Host
7 | }
--------------------------------------------------------------------------------
/EnumColors.ps1:
--------------------------------------------------------------------------------
1 | # EnumColors.ps1
2 | [Enum]::GetValues([System.ConsoleColor]) | select-object `
3 | @{"Name" = "Name"; "Expression" = {$_}},
4 | @{"Name" = "Dec"; "Expression" = {[Int] $_}},
5 | @{"Name" = "Hex"; "Expression" = {"0x{0:X1}" -f [Int] $_}} |
6 | format-table -auto
7 |
--------------------------------------------------------------------------------
/ConsoleColors.ps1:
--------------------------------------------------------------------------------
1 | For($i = 0;$i -le 15;$i++){
2 | For($j = 0;$j -le 15;$j++){
3 | $background = '{0:X}' -f $i
4 | $foreground = '{0:X}' -f $j
5 | cmd /c color $background$foreground
6 | Write-Host "Color scheme # $background$foreground"
7 | Sleep 1
8 | }
9 | }
--------------------------------------------------------------------------------
/GeneratePassword.ps1:
--------------------------------------------------------------------------------
1 | # Requires the Basic Authentication feature of IIS
2 |
3 | Function Generate-Password{
4 | Param(
5 | [int]$Length = 8,
6 | [int]$numberOfSymbols = 1
7 | )
8 | [System.Web.Security.Membership]::GeneratePassword($Length,$numberOfSymbols)
9 | }
10 |
--------------------------------------------------------------------------------
/Networking/BadHorse.ps1:
--------------------------------------------------------------------------------
1 | $net = "162.168.205."
2 | 131..157 | %{
3 | Do{
4 | If($name = Resolve-DnsName "$net$_" -Type PTR -ErrorAction SilentlyContinue){
5 | break
6 | }
7 | Sleep 10
8 | }Until($name)
9 | "$net$_" + " . . . . " + $name.NameHost
10 | }
--------------------------------------------------------------------------------
/Networking/ConnectivityReport.ps1:
--------------------------------------------------------------------------------
1 | Do {
2 | If(Test-Connection "8.8.8.8" -Count 1 -Quiet -ea SilentlyContinue){
3 | Write-Host "$(Get-Date) Success"
4 | } Else{
5 | Write-Host "$(Get-Date) FAILED" -ForegroundColor Red
6 | }
7 | Sleep 10
8 | } Until ((Get-Date) -gt [datetime]"7/19/2012 7:00:00 AM")
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PowerShell-Depot [
](https://msdn.microsoft.com/en-us/powershell/)
2 | [](https://www.paypal.me/simplescripter)
3 |
4 | A collection of random PowerShell scripts
5 |
--------------------------------------------------------------------------------
/QueryLiveEventLog.ps1:
--------------------------------------------------------------------------------
1 | $filter = @"
2 |
3 |
4 |
8 |
9 |
10 | "@
11 |
12 | Get-WinEvent -FilterXml $filter
13 |
--------------------------------------------------------------------------------
/ActiveDirectory/DirectorySearcher.ps1:
--------------------------------------------------------------------------------
1 | $root = [ADSI]""
2 | $rootDN = $root.distinguishedName
3 | $searcher = New-Object System.DirectoryServices.DirectorySearcher $rootDN
4 | $name = Read-Host "What name are you looking for?"
5 | $searcher.Filter = "(&(objectCategory=user)(sAMAccountName=$name))"
6 | ($searcher.Findall())[0].properties
--------------------------------------------------------------------------------
/EventRegistrationExample.ps1:
--------------------------------------------------------------------------------
1 | cls
2 | $query = "SELECT * FROM __instanceCreationEvent Within 3 WHERE TargetInstance ISA 'Win32_Process'"
3 | Register-WmiEvent -Query $query -Action {Write-Host "$($event.timeGenerated) : $($event.sourceEventArgs.NewEvent.TargetInstance.Name) launched" -ForegroundColor Red}
4 | Set-Alias ue Unregister-Event
--------------------------------------------------------------------------------
/DSC/Partial_Configs_Demo/2-First_Config.ps1:
--------------------------------------------------------------------------------
1 | Configuration AdatumEnvVars
2 | {
3 | Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
4 |
5 | Environment AdatumEnvVar1
6 | {
7 | Ensure = 'Present'
8 | Name = 'AdatumEnvVar1'
9 | Value = '1'
10 | }
11 | }
12 |
13 | AdatumEnvVars
14 |
--------------------------------------------------------------------------------
/GetOctoCatWisdom.ps1:
--------------------------------------------------------------------------------
1 | Function Get-OctoCatWisdom {
2 | # ReST Demo
3 |
4 | # Many sites, including GitHub, now require TLS 1.2 or greater, so let's enable it:
5 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
6 |
7 | $url = 'https://api.github.com/octocat'
8 | Invoke-RestMethod $url
9 | }
--------------------------------------------------------------------------------
/QuerySavedEventLog.ps1:
--------------------------------------------------------------------------------
1 | $filter = @"
2 |
3 |
8 |
9 |
10 | "@
11 |
12 | Get-WinEvent -FilterXml $filter
--------------------------------------------------------------------------------
/SortProperty.ps1:
--------------------------------------------------------------------------------
1 | Function Sort-Property{
2 | [CmdletBinding()]
3 | Param(
4 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
5 | $object
6 | )
7 | Process{
8 | $props = $object | Get-Member -MemberType *Property | Sort Name | Select -ExpandProperty Name
9 | $object | Format-List -Property $props
10 | }
11 | }
--------------------------------------------------------------------------------
/GetGPOVersion.ps1:
--------------------------------------------------------------------------------
1 | Import-Module GroupPolicy
2 | Get-GPO -all |
3 | Select-Object DisplayName, `
4 | @{Label='User AD';Expression={$_.User.DSVersion}}, `
5 | @{Label='User SysVol';Expression={$_.User.SysVolVersion}}, `
6 | @{Label='Computer AD';Expression={$_.Computer.DSVersion}}, `
7 | @{Label='Computer SysVol';Expression={$_.Computer.SysVolVersion}} |
8 | Format-Table -auto
--------------------------------------------------------------------------------
/MonitorGroupChanges.ps1:
--------------------------------------------------------------------------------
1 | $query = "Select * From __InstanceModificationEvent within 5 Where TargetInstance
2 | ISA 'ds_group' AND TargetInstance.ds_name = 'Domain Admins'"
3 | Register-WMIEvent -query $query -namespace "root/directory/LDAP" -sourceIdentifier "AdminChange" `
4 | -action {Write-Host "Domain Admins has changed!!!" -Foregroundcolor Red -BackgroundColor Black}
5 |
--------------------------------------------------------------------------------
/DSC/Partial_Configs_Demo/4-Deploy_Configs.ps1:
--------------------------------------------------------------------------------
1 | Publish-DscConfiguration -Path .\AdatumEnvVars -ComputerName 'localhost'
2 | Publish-DscConfiguration -Path .\AdatumRegistry -ComputerName 'localhost'
3 | Start-DscConfiguration -UseExisting -ComputerName 'localhost'
4 |
5 | Get-ItemProperty -Path 'HKLM:\Software\AdatumRegKey1'
6 | [Environment]::GetEnvironmentVariable("AdatumEnvVar1","Machine")
7 |
--------------------------------------------------------------------------------
/ImportandUpdateCSV.ps1:
--------------------------------------------------------------------------------
1 | Param(
2 | $inputFile = "C:\Users\Shawn.ELYSIUM\Desktop\10325 to Delete\test.csv",
3 | $outputFile = $inputFile
4 | )
5 | $results = Import-CSV $inputFile |
6 | Select Type,ComputerName,@{Name="Success";Expression= `
7 | {Test-Connection -ComputerName $_.ComputerName -Count 1 -Quiet}}
8 | $results | Export-CSV -Force -NoTypeInformation -Path $outputFile
9 |
--------------------------------------------------------------------------------
/DSC/Partial_Configs_Demo/3-Second_Config.ps1:
--------------------------------------------------------------------------------
1 | Configuration AdatumRegistry
2 | {
3 | Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
4 |
5 | Registry AdatumReg1
6 | {
7 | Ensure = 'Present'
8 | Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\AdatumRegKey1'
9 | ValueName = 'AdatumRegVal1'
10 | ValueData = '1'
11 | }
12 | }
13 |
14 | AdatumRegistry
--------------------------------------------------------------------------------
/Progress.ps1:
--------------------------------------------------------------------------------
1 | for($i = 327; $i -lt 412; $i++ ) {
2 | $percent = (($i/412)*100)
3 | $actual = "{0:N}" -f $percent
4 | write-progress -activity "Counting Down" -status "Percent Total Hours Complete (Actual = $actual)" -percentcomplete $percent
5 | for($j = 1; $j -lt 101; $j++){
6 | Sleep -Milliseconds 600
7 | write-progress -activity "Counting Down" -status "Minute Tracker" -percentcomplete $j -Id 1
8 | }
9 | }
--------------------------------------------------------------------------------
/CopyDirectoryToSystems.ps1:
--------------------------------------------------------------------------------
1 | # An example for copying a source folder to one or more destination systems
2 |
3 | $folderPath = 'E:\drivers'
4 | $computers = Import-CSV E:\computers.csv
5 | ForEach($computer in $computers){
6 | New-PSDrive -Name Z -Root ("\\" + $computer.name + '\C$') -PSProvider FileSystem
7 | Copy-Item -Path $folderPath -Recurse -Force -Destination Z:\
8 | Remove-PSDrive -Name Z -Force
9 | }
10 |
--------------------------------------------------------------------------------
/DSC/FileServer.ps1:
--------------------------------------------------------------------------------
1 | Configuration FileServer {
2 | Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
3 | Node 'ServerA' {
4 | WindowsFeature FS {
5 | Name = 'FS-FileServer'
6 | Ensure = 'Present'
7 | }
8 |
9 | WindowsFeature Dedup {
10 | Name = 'FS-Data-Deduplication'
11 | Ensure = 'Present'
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/NewLocalUserFromSerialNumber.ps1:
--------------------------------------------------------------------------------
1 | # Requires an input CSV with SerialNumber and LocalUser info
2 | $input = Import-CSV E:\serials.txt
3 | $lookupTable = @{}
4 | ForEach($row in $input){
5 | $lookupTable.Add($row.SerialNumber,$row.LocalUser)
6 | }
7 | $serial = Get-CIMInstance Win32_BIOS | Select-Object -ExpandProperty SerialNumber
8 | $user = $lookTable.$serial
9 | New-LocalUser $user -NoPassword | Add-LocalGroupMember -Name 'Administrators'
--------------------------------------------------------------------------------
/DetectUSB-Remove.ps1:
--------------------------------------------------------------------------------
1 | Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='USBFilter'" |
2 | Remove-WmiObject -Verbose
3 |
4 | Get-WMIObject -Namespace root\Subscription -Class LogFileEventConsumer -Filter "Name='USBConsumer'" |
5 | Remove-WmiObject -Verbose
6 |
7 | Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding -Filter "__Path LIKE '%USBFilter%'" |
8 | Remove-WmiObject -Verbose
--------------------------------------------------------------------------------
/GetChuck.ps1:
--------------------------------------------------------------------------------
1 | Function Get-Chuck {
2 | $headers=@{}
3 | $headers.Add("x-rapidapi-host", "matchilling-chuck-norris-jokes-v1.p.rapidapi.com")
4 | $headers.Add("x-rapidapi-key", "ab827a7c18msh69957d2992bc00ap1fa16ejsnbc26c13c911e")
5 | $headers.Add("accept", "application/json")
6 | $response = Invoke-RestMethod -Uri 'https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random' -Method GET -Headers $headers
7 | $response.value
8 | }
9 |
--------------------------------------------------------------------------------
/ArchiveFiles.ps1:
--------------------------------------------------------------------------------
1 | Function Archive-File{
2 | [CmdletBinding()]
3 | Param(
4 | [string]$searchPath = "E:\",
5 | [Parameter(Mandatory=$true)][string[]]$extensions
6 | )
7 | Get-Childitem -recurse -path $searchPath -Include $extensions |
8 | ForEach-Object {
9 | Move-Item $PSItem.FullName -Destination "C:\Archive\$($PSItem.BaseName)-$(Get-Random -Minimum 1000000 -Maximum 100000000)$($PSItem.Extension)"
10 | }
11 | }
--------------------------------------------------------------------------------
/DSC/DisableScreenLock.ps1:
--------------------------------------------------------------------------------
1 | Configuration "Screen"
2 | {
3 | Import-DscResource -ModuleName PSDesiredStateConfiguration
4 | Node localhost
5 | {
6 | Registry 'ACSettingIndex'
7 | {
8 | Ensure = 'Present'
9 | Key = 'HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Power\PowerSettings\3C0BC021-C8A8-4E07-A973-6B14CBCB2B7E'
10 | ValueName = 'ACSettingIndex'
11 | ValueType = 'DWord'
12 | ValueData = '0'
13 | }
14 | }
15 | }
16 | Screen
--------------------------------------------------------------------------------
/ActiveDirectory/GetADAttributes.ps1:
--------------------------------------------------------------------------------
1 | Function Get-AdAttributes {
2 | Param(
3 | [Parameter(Mandatory=$true)]
4 | [string]$AdClass
5 | )
6 |
7 | $Schema = [DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema()
8 | $Schema.FindClass("$AdClass").MandatoryProperties | Select Name, Syntax, IsSingleValued, CommonName
9 | $Schema.FindClass("$AdClass").OptionalProperties | Select Name, Syntax, IsSingleValued, CommonName
10 | }
--------------------------------------------------------------------------------
/CustomPipelineProperty.ps1:
--------------------------------------------------------------------------------
1 | # An example of adding a custom property to an object in the PowerShell pipeline.
2 | # Rather than using Select-Object to create the property on demand, updating the
3 | # type data for the object itself allows you to create a "permanent" object property.
4 | # The code could be added to your PowerShell profile
5 |
6 | Update-TypeData -TypeName Microsoft.ActiveDirectory.Management.ADComputer -Membertype ScriptProperty -MemberName Computername -Value {$this.Name}
--------------------------------------------------------------------------------
/DSC/BuildFeatureList.ps1:
--------------------------------------------------------------------------------
1 | # We can pull the existing feature list from a server and add it to a ConfigurationData hash table.
2 | #To speed up the process, do this:
3 |
4 | $list = Get-WindowsFeature | Where-Object Installed -eq $true | Select-Object -ExpandProperty Name
5 | $list = $list -join ",`n"
6 |
7 | @"
8 | `$configData = @{
9 | AllNodes = @(
10 | NodeName = "*"
11 | WindowsFeature = @(
12 | $($list)
13 | )
14 | )
15 | }
16 | "@
--------------------------------------------------------------------------------
/Networking/PingSweepInvokeParallel.ps1:
--------------------------------------------------------------------------------
1 | # Requires Rambling Cookie Monster's Invoke-Parallel function: https://gallery.technet.microsoft.com/scriptcenter/Run-Parallel-Parallel-377fd430/view/Discussions
2 |
3 | $results = 1..254 | Invoke-Parallel -Throttle 32 -ScriptBlock {
4 | If(Test-Connection "192.168.1.$_" -Count 1 -Quiet){
5 | Write-Host "192.168.1.$_`n" -ForegroundColor Green -NoNewline
6 | }Else{
7 | Write-Host "192.168.1.$_`n" -ForegroundColor Red -NoNewline
8 | }
9 | }
--------------------------------------------------------------------------------
/MoveHomeFolders.ps1:
--------------------------------------------------------------------------------
1 | $OldPath = "C:\Home"
2 | $NewPath = "D:\HomeArchive"
3 | $UserList = "C:\users.txt"
4 |
5 | Get-Content $UserList | foreach{
6 | Copy-Item -Recurse -Force $OldPath\$_ $NewPath\$_ -ErrorVariable moveErr -ErrorAction SilentlyContinue
7 | If ($moveErr = $NULL){
8 | Write-Host -ForeGroundColor red $_ ": MOVE FAILED"
9 | $moveErr = $NULL}
10 | Else{
11 | Remove-Item -Recurse -Force $OldPath\$_
12 | Write-Host -ForeGroundColor green $_ ": SUCCESS"
13 | }
14 | }
--------------------------------------------------------------------------------
/Caesar.ps1:
--------------------------------------------------------------------------------
1 | Function Add-Characters{
2 | Param(
3 | [char]$i
4 | )
5 | If([int]$i + $places -gt 90){
6 | $result=[char]((([int]$i + $places) - 90) + 64)
7 | }Else{
8 | $result=[char]([int]$i + $places)
9 | }
10 | Write-Output $result
11 | }
12 | Function Caesar{
13 | Param(
14 | [string]$string,
15 | [int]$places
16 | )
17 | #Write-Host "Shifted $places Places"
18 | ForEach($char in [char[]]$string.ToUpper()){$result+= Add-Characters $char}
19 | Write-Output "Shifted $places Places: $result"
20 | }
21 |
--------------------------------------------------------------------------------
/FinallyDemo.ps1:
--------------------------------------------------------------------------------
1 | Try{
2 | Get-Service NONE -ErrorAction Stop
3 | }
4 | Catch{
5 |
6 | }
7 | "This code runs"
8 |
9 | Try{
10 | Get-Service NONE -ErrorAction Stop
11 | }
12 | Catch{
13 |
14 | }Finally{
15 | "This code runs"
16 | }
17 |
18 | Try{
19 | Get-Service NONE -ErrorAction Stop
20 | }
21 | Catch{
22 | Return # or Exit
23 | }
24 | "This code does NOT run"
25 |
26 | Try{
27 | Get-Service NONE -ErrorAction Stop
28 | }
29 | Catch{
30 | Return #or Exit
31 | }Finally{
32 | "This code runs"
33 | }
--------------------------------------------------------------------------------
/ImportHashFromCSV.ps1:
--------------------------------------------------------------------------------
1 | #this is a work in progress; NOT complete yet
2 |
3 | cls
4 | $table = Import-Csv .\test.csv
5 | $keyProperty = "Name"
6 | $properties = $table | Get-Member -MemberType NoteProperty |
7 | Where-Object {$_.Name -ne $keyProperty} |
8 | Select Name
9 | $hash = @{}
10 | $headerarray = @()
11 | For($i = 0;$i -lt $properties.count;$i++){
12 | $headerarray += $($row.(($properties[$i]).name))
13 | }
14 | ForEach ($row in $table){
15 | $hash[$row.Name] = $headerarray
16 | $headerarray = @()
17 | }
18 |
19 | $hash
--------------------------------------------------------------------------------
/ChangeText.ps1:
--------------------------------------------------------------------------------
1 | Function Change-Text {
2 | Param(
3 | [string]$oldString,
4 | [string]$newString
5 | )
6 | ForEach ($file in $input){
7 | Write-Host -Fore green "Changing $file"
8 | $filestream = Get-Content $file
9 | Clear-Content $file
10 | ForEach($line in $filestream){
11 | $result = $result + ($line.Replace($oldString, $newString)) + "`n"
12 | }
13 | Set-Content $file $result
14 | $line = $NULL
15 | $result = $NULL
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ActiveDirectory/MoveComputers.ps1:
--------------------------------------------------------------------------------
1 | Import-Module ActiveDirectory
2 | $domain = "DC=Contoso,DC=Com"
3 | $OUs = Get-ADOrganizationalUnit -Filter * | Select-Object Name
4 | $OUarray = @()
5 | ForEach($name in $OUs){
6 | $OUarray+= $name.name
7 | }
8 | ForEach($computer in (Get-ADComputer -filter * -SearchBase "CN=Computers,$domain")){
9 | $first5 = ($computer.Name).SubString(0,5)
10 | If($OUarray -contains "$first5"){
11 | Move-ADObject $computer "OU=$first5,$domain"
12 | Write-Host "Moved $computer to OU=$first5,$domain"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Azure/Point2SiteWin10Cert.ps1:
--------------------------------------------------------------------------------
1 | $certParams = @{
2 | Type = 'Custom'
3 | KeySpec = 'Signature'
4 | KeyExportPolicy = 'Exportable'
5 | HashAlgorithm = 'sha256'
6 | KeyLength = 2048
7 | CertStoreLocation = "Cert:\CurrentUser\My"
8 | }
9 | $cert = New-SelfSignedCertificate @certParams -Subject 'CN=P2SRootCert' -KeyUsage 'CertSign' -KeyUsageProperty 'Sign'
10 |
11 | New-SelfSignedCertificate @certParams -DnsName 'P2SChildCert' -Subject 'CN=P2SChildCert' `
12 | -Signer $cert -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2")
13 |
--------------------------------------------------------------------------------
/SkylakeCheck.ps1:
--------------------------------------------------------------------------------
1 | #$systems = Get-Content C:\script\systems.txt
2 | $systems = 'localhost'
3 | $skylakeList = Invoke-WebRequest 'http://ark.intel.com/products/codename/37572/Skylake#@All'
4 | ForEach ($system in $systems){
5 | $processor = ((Get-WMIObject win32_Processor -ComputerName $system).name) `
6 | -replace '.*(\w{0,1}\d{4}\w{0,1}).*','$1'
7 | $properties = @{
8 | ComputerName = $system
9 | Skylake = $skylakeList -match $processor
10 | }
11 | New-Object -TypeName PSObject -Property $properties
12 | }
13 |
14 |
--------------------------------------------------------------------------------
/RemoveArchiveAttribute.ps1:
--------------------------------------------------------------------------------
1 | $path = 'E:\Mod01\Democode'
2 | $files = Get-ChildItem -Path $path -Recurse
3 | $archiveAttribute = [System.IO.FileAttributes]::Archive
4 |
5 | Foreach($file in $files){
6 | If((Get-ItemProperty -Path $file.FullName).Attributes -band $archiveAttribute){
7 | Write-Host "$($file.Name) archive bit set" -ForegroundColor Red
8 | $archiveRemoved = (Get-ItemProperty $file.fullname).attributes -bxor $archiveAttribute
9 | Set-ItemProperty -Path $file.FullName -Name Attributes -Value $archiveRemoved
10 | }
11 | }
--------------------------------------------------------------------------------
/Switch-Regex.ps1:
--------------------------------------------------------------------------------
1 | # This code example is from Jeffrey Hicks at http://mcpmag.com/articles/2010/10/05/switch-way-did-they-go.aspx
2 |
3 | $x=Read-host "enter something"
4 | Switch -regex ($x) {
5 | \d+ {
6 | write-host "You entered one or more numbers: $($matches.item(0))"
7 | }
8 | \w+ {
9 | write-host "You entered one or more alpha characters: $($matches.item(0))"
10 | }
11 | \W+ {
12 | write-host "You entered one or more non-alphanumeric characters: $($matches.item(0))"
13 | }
14 | Default {
15 | write-host "I don't know what you entered: $x"
16 | }
17 | }
--------------------------------------------------------------------------------
/DSC/BuildAllNodesList.ps1:
--------------------------------------------------------------------------------
1 | Function Build-AllNodesList {
2 | #requires -module ActiveDirectory
3 | $computerList = Get-ADComputer -Filter *
4 | $nodes = @()
5 | ForEach ($computer in $computerList){
6 | $nodes += @"
7 | @{
8 | NodeName = "$($computer.Name)"
9 | }`n
10 | "@
11 | }
12 | $AllNodeString = @"
13 | `$ConfigurationData =
14 | @{
15 | AllNodes = @(
16 | $nodes
17 | )
18 | }
19 | "@
20 | Write-Output $AllNodeString
21 | }
--------------------------------------------------------------------------------
/GetColor.ps1:
--------------------------------------------------------------------------------
1 | # Get-Color.ps1
2 | # Written by Bill Stewart (bill.stewart@frenchmortuary.com)
3 |
4 | param([Switch] $Table)
5 |
6 | # If -table exists, output a color table.
7 | if ($Table) {
8 | for ($bg = 0; $bg -lt 0x10; $bg++) {
9 | for ($fg = 0; $fg -lt 0x10; $fg++) {
10 | write-host -nonewline -background $bg -foreground $fg `
11 | (" {0:X}{1:X} " -f $bg,$fg)
12 | }
13 | write-host
14 | }
15 | exit
16 | }
17 |
18 | # Output the current colors as a string.
19 | "{0:X}{1:X}" -f [Int] $HOST.UI.RawUI.BackgroundColor,
20 | [Int] $HOST.UI.RawUI.ForegroundColor
21 |
--------------------------------------------------------------------------------
/ActiveDirectory/OldUser.ps1:
--------------------------------------------------------------------------------
1 | Function Global:Get-OldUser{
2 | Param(
3 | $days = 90,
4 | $ignoreNewUsers = $true
5 | )
6 | Import-Module ActiveDirectory
7 | $interval = New-TimeSpan -Days $days
8 | If($ignoreNewUsers){
9 | Get-ADUser -filter * -Properties lastlogontimestamp |
10 | Where-Object{($_.lastlogontimestamp) -and ([datetime]::FromFileTime($_.lastlogontimestamp) -le ((Get-Date) - $interval))}
11 | }
12 | Else{
13 | Get-ADUser -filter * -Properties lastlogontimestamp |
14 | Where-Object{[datetime]::FromFileTime($_.lastlogontimestamp) -le ((Get-Date) - $interval)}
15 | }
16 | }
--------------------------------------------------------------------------------
/GetHash.ps1:
--------------------------------------------------------------------------------
1 | # From http://www.vistax64.com/powershell/207882-get-md5-digest-powershell.html
2 | function Global:Get-Hash ($file) {
3 | $hasher = [System.Security.Cryptography.MD5]::Create()
4 | $inputStream = New-Object System.IO.StreamReader ($file)
5 | $hashBytes = $hasher.ComputeHash($inputStream.BaseStream)
6 | $inputStream.Close()
7 | $builder = New-Object System.Text.StringBuilder
8 | $hashBytes | Foreach-Object { [void] $builder.Append($_.ToString("X2")) }
9 | $output = New-Object PsObject
10 | $output | Add-Member NoteProperty HashValue ([string]$builder.ToString())
11 | $output.hashvalue
12 | }
13 |
14 |
--------------------------------------------------------------------------------
/RegisterRepo.ps1:
--------------------------------------------------------------------------------
1 | Function Register-Repo {
2 | Param(
3 | [Parameter(Mandatory=$true)]
4 | [string]$name,
5 |
6 | [Parameter(Mandatory=$true)]
7 | [string]$sourceLocation,
8 |
9 | [ValidateSet('Trusted','Untrusted')]
10 | [string]$installationPolicy = 'Trusted'
11 | )
12 | # Many sites, including GitHub, now require TLS 1.2 or greater, so let's enable it:
13 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
14 |
15 | Register-PSRepository -Name $name -SourceLocation $sourceLocation -InstallationPolicy $installationPolicy
16 | }
--------------------------------------------------------------------------------
/WindowsTerminalExamples.ps1:
--------------------------------------------------------------------------------
1 | # when we don't require variable replacement, using single quotes
2 | start-process wt 'new-tab -p "Windows PowerShell" ; split-pane -p "PowerShell (Core)" ; split-pane -H wsl.exe'
3 |
4 | # requiring variable replacement, using double quotes
5 | $ThirdPane = "wsl.exe"
6 | start-process wt "new-tab -p `"Windows PowerShell`"; split-pane -p `"PowerShell `(Core`)`"; split-pane -H $ThirdPane"
7 |
8 | wt -p "Windows PowerShell" `; split-pane -p "PowerShell (Core)" `; split-pane -H wsl.exe
9 |
10 | wt --% -p "Windows PowerShell" ; split-pane -p "PowerShell (Core)" ; split-pane -H "Ubuntu"
11 |
12 |
13 |
--------------------------------------------------------------------------------
/GetJava.ps1:
--------------------------------------------------------------------------------
1 | Function Get-Java{
2 | Param(
3 | [switch]$raw,
4 | [switch]$novisualization
5 | )
6 | $counter = "\Process(javaw)\Working Set - Private"
7 | $sample = Get-Counter $counter
8 | If($raw){
9 | Write-OutPut $sample
10 | }
11 | Else{
12 | $text = "JAVAW Private Working Set Memory at $((Get-Date).ToLongTimeString()): {0:N2} MB" -f ($($sample.CounterSamples).CookedValue / 1MB)
13 | If($novisualization){
14 | Write-Host -ForegroundColor DarkGreen $text
15 | }
16 | Else{
17 | Write-Host -ForegroundColor DarkGreen "$text $("I" * (($($sample.CounterSamples).CookedValue / 1MB) / 10))"
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/MixLetters.ps1:
--------------------------------------------------------------------------------
1 | Clear-Host
2 | $message = Read-Host "Enter your message"
3 | $mixedWord = $null
4 | $words = $message.split()
5 | foreach($word in $words){
6 | If($word.Length -lt 4){
7 | $mixedWord += $word + " "
8 | }else{
9 | $first = $word.substring(0,1)
10 | $last = $word.substring(($word.length - 1),1)
11 | $middleLetters = $word.Substring(1,($word.Length -2))
12 | $midLetterCount = $middleLetters.Length
13 | $randomOrder = $middleLetters.ToCharArray() | Get-Random -Count $midLetterCount | Out-String
14 | $randomOrder = $randomOrder -replace "`n", ""
15 | $mixedWord += $first + $randomOrder + $last + " "
16 | }
17 | }
18 |
19 | $mixedWord
--------------------------------------------------------------------------------
/SetRecordingReminder.ps1:
--------------------------------------------------------------------------------
1 | Function Set-RecordingReminder {
2 | Param(
3 | [string]$soundFile = "D:\Users\Shawn.ELYSIUM\Documents\Scripting Reference\PowerShell\psinvaders\samples\insertcoin.wav",
4 | [Parameter(Mandatory=$true)]
5 | [datetime]$reminderTime,
6 | [int]$offset = 30 # number of seconds earlier than $ReminderTime to set reminder
7 | )
8 | $obj = New-Object System.Media.SoundPlayer
9 | $obj.SoundLocation = $soundFile
10 | Do{
11 | Start-Sleep 10
12 | }Until((Get-Date) -ge (($reminderTime).AddSeconds(-$offset)))
13 | For($i=1;$i -le 3;$i++){
14 | $obj.Play()
15 | Start-Sleep 1
16 | }
17 | }
--------------------------------------------------------------------------------
/StripSignature.ps1:
--------------------------------------------------------------------------------
1 | # A function to strip the digital signature block from
2 | # a signed script.
3 | # Example 1: dir file.ps1 | Strip-Sig
4 | # Example 2: dir -filter *.ps1 | Strip-Sig
5 | Function global:Strip-Signature {
6 | $sig = "# SIG # Begin signature block"
7 | ForEach ($_ in $input){
8 | $j = $null
9 | Write-Host -ForegroundColor Green "Stripping $_"
10 | $filestream = cat $_
11 | Clear-Content $_
12 | ForEach($i in $filestream){
13 | If($i -ne $sig){
14 | $j = $j + $i + "`n"
15 | }Else{Break}
16 | }
17 | Set-Content $_ $j
18 | }
19 | }
20 |
21 |
22 |
--------------------------------------------------------------------------------
/ArrayListLoopingExample.ps1:
--------------------------------------------------------------------------------
1 | # An example of looping through an arraylist of computer names and removing
2 | # those names that responded. Loops until all systems have been contacted.
3 |
4 | [System.Collections.ArrayList]$computerList = 'LON-DC1','LON-SVR1','LON-CL1'
5 | Do {
6 | [array]$list = $computerList
7 | ForEach($computer in $list){
8 | If(Test-Connection -ComputerName $computer -Count 1 -Quiet){
9 | $computerList.Remove($computer)
10 | }
11 | }
12 | If($computerList.Count -gt 0){Start-Sleep 5}
13 | }Until($computerList.Count -eq 0)
14 | Write-Host 'All systems in $computerList have been contacted.' -ForegroundColor DarkCyan -BackgroundColor Yellow
--------------------------------------------------------------------------------
/Networking/Find_Wireless_Adapters.ps1:
--------------------------------------------------------------------------------
1 | $physicalAdapters = Get-WMIObject -Class Win32_NetworkAdapter -Filter "PhysicalAdapter=$true"
2 | $adapterNames = @()
3 | ForEach ($adapter in $physicalAdapters){
4 | $adapterNames += $adapter.Name
5 | }
6 |
7 | Get-WMIObject -Namespace root\WMI -Class MSNdis_PhysicalMediumType |
8 | Where-Object {$_.InstanceName -in $adapterNames} |
9 | Select InstanceName, @{
10 | Name='MediumType'
11 | Expression={
12 | Switch ($_.NdisPhysicalMediumType){
13 | 0 {"Ethernet or Other"}
14 | 9 {"Wifi"}
15 | 10 {"Bluetooth"}
16 | default {"Unknown"}
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/EncodeFile.ps1:
--------------------------------------------------------------------------------
1 | Function Encode-File {
2 | [CmdletBinding()]
3 | Param(
4 | [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
5 | [string[]]$file,
6 |
7 | [string]$saveAsHTML
8 | )
9 | Begin{
10 | $html = @"
11 |
12 |
 | " -FilePath $saveAsHTML
20 | }Else{
21 | Write-Output $Base64
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/Networking/PingSweep.ps1:
--------------------------------------------------------------------------------
1 | WorkFlow PingSweep{
2 | $computers = @()
3 | For ($i = 1; $i -le 254; $i++){$computers += "192.168.0.$i"}
4 | ForEach -Parallel ($computer in $computers){
5 | If(Test-NetConnection -computerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue){
6 | Write-Output -InputObject "$computer,ONLINE"
7 | }else{
8 | Write-Output -InputObject "$computer,OFFLINE"
9 | }
10 | }
11 | }
12 |
13 | PingSweep | ForEach-Object {
14 | $ip = $_.Split(",")[0]
15 | $status = $_.Split(",")[1]
16 | If($status -eq 'ONLINE'){
17 | Write-Host "$ip" -ForegroundColor Green
18 | }Else{
19 | Write-Host "$ip" -ForegroundColor Red
20 | }
21 | }
--------------------------------------------------------------------------------
/ConsoleTextColorCombos.ps1:
--------------------------------------------------------------------------------
1 | # Displays the possible combinations of console colors, foreground and background
2 |
3 | # Possible console text and background colors:
4 | $colors =
5 | 'Black',
6 | 'Blue',
7 | 'Cyan',
8 | 'DarkBlue',
9 | 'DarkCyan',
10 | 'DarkGray',
11 | 'DarkGreen',
12 | 'DarkMagenta',
13 | 'DarkRed',
14 | 'DarkYellow',
15 | 'Gray',
16 | 'Green',
17 | 'Magenta',
18 | 'Red',
19 | 'White',
20 | 'Yellow'
21 |
22 | ForEach ($foregroundColor in $colors){
23 | ForEach ($backgroundColor in $colors){
24 | Write-Host "$i $foregroundColor on $backgroundColor" -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
25 | }
26 | }
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/ComparePPTHashes.ps1:
--------------------------------------------------------------------------------
1 | Param(
2 | $firstFolder,
3 | $secondFolder
4 | )
5 |
6 | $files = Get-ChildItem $firstFolder
7 | #$files2 = Get-ChildItem $secondFolder | Select -ExpandProperty FullName
8 | ForEach($file in $files){
9 | $File1 = Get-FileHash $file.FullName -Algorithm SHA1 | Select -ExpandProperty Hash
10 | $File2 = Get-FileHash (Join-Path $secondFolder $file.Name) -Algorithm SHA1 | Select -ExpandProperty Hash
11 | If($File1 -eq $File2){
12 | $result = 'SAME'
13 | }Else{
14 | $result = 'CHANGED'
15 | }
16 | $props = [ordered]@{
17 | 'Name' = $file.Name
18 | 'File1' = $file1
19 | 'File2' = $file2
20 | 'Comparison' = $result
21 | }
22 | New-Object -TypeName psobject -Property $props
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/DSC/PackageResource.ps1:
--------------------------------------------------------------------------------
1 | #Get-DscResource -Name Package -Syntax
2 | # Download the 7-Zip .MSI package
3 | # Use InstEd to extract the Name and ProductID from the MSI. Use Tables -> Properties in the InstEd software
4 | # Run as admin
5 |
6 | Configuration PackageResource {
7 |
8 | Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
9 | Node StudentServer {
10 | Package 7Zip {
11 | Name = '7-Zip 17.00 (x64 edition)'
12 | Path = 'C:\Users\Student\Downloads\7z1700-x64.msi'
13 | ProductID = '23170F69-40C1-2702-1700-000001000000'
14 | Ensure = "Present"
15 | }
16 | }
17 | }
18 |
19 | PackageResource -OutputPath C:\PackageTest
20 |
21 | Start-DscConfiguration -Path C:\PackageTest -Verbose -Wait
--------------------------------------------------------------------------------
/Speak.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | This is a work in progress. Currently, the script will create a scheduled task on the
3 | remote machine, BUT
4 |
5 | --The script is scheduled for ONE DAY after it runs
6 | --Instead of scheduling the task for the exact second, it schedules it for the
7 | next full minute
8 | --When I try executing the scheduled task manually, it doesn't "speak" anyway
9 |
10 | #>
11 |
12 | $computer = "XPS"
13 | [WMIClass]$wmi = "\\$computer\root\CIMv2:Win32_ScheduledJob"
14 | $5Seconds = New-TimeSpan -Seconds 5
15 | $OS = gwmi Win32_OperatingSystem -ComputerName $computer
16 | $newTime = ($OS.ConvertToDateTime($OS.LocalDateTime)) + $5Seconds
17 | $scheduleTime = $OS.ConvertFromDateTime($newTime)
18 | $wmi.Create("wscript.exe c:\temptemp\voice.vbs", $scheduleTime, $False, $Null , $Null , $True)
19 |
20 |
--------------------------------------------------------------------------------
/Networking/CopyURL.ps1:
--------------------------------------------------------------------------------
1 | Function Copy-Cam{
2 | Param(
3 | $script:camURL = $(Read-Host "URL")
4 | )
5 | If (! $sourcefile){
6 | $script:sourcefile = 'C:\Users\Shawn.ELYSIUM\Desktop\Anony fun\anony-stripped.htm'
7 | }
8 |
9 | Get-content $sourcefile | Where-Object{$_ -like "*$camURL*"}
10 | }
11 |
12 | Function Swap{
13 | Param(
14 | $filePath = 'C:\Users\Shawn.ELYSIUM\Desktop\Anony fun\anony-on-06.htm'
15 | )
16 | If(!(Test-Path $filePath)){
17 | " " | Out-File $filePath
18 | }
19 | If((Get-Content $filePath | Measure-Object).count -ge 10){
20 | Write-Host -ForegroundColor Red "$filePath is full."
21 | Return
22 | }
23 | $line = Copy-Cam
24 | $line | Out-File $filePath -Append
25 | (Get-Content $sourcefile) -notlike "*$camURL*" | Out-File $sourcefile
26 | }
27 |
--------------------------------------------------------------------------------
/AudibleNotification.ps1:
--------------------------------------------------------------------------------
1 | $obj = New-Object System.Media.SoundPlayer
2 | $obj.SoundLocation = "D:\Users\Shawn.ELYSIUM\Documents\Scripting Reference\PowerShell\psinvaders\samples\insertcoin.wav"
3 | $ok = $false
4 | Do{
5 | Sleep 20
6 | If(Test-NetConnection 8.8.8.8 -InformationLevel Quiet){
7 | $obj.Play()
8 | Sleep 1
9 | $obj.Play()
10 | Sleep 1
11 | $obj.Play()
12 | Sleep 1
13 | $obj.Play()
14 | Sleep 1
15 | $obj.Play()
16 | Sleep 1
17 | $obj.Play()
18 | Sleep 1
19 | $obj.Play()
20 | Sleep 1
21 | $obj.Play()
22 | Sleep 1
23 | $obj.Play()
24 | Sleep 1
25 | $obj.Play()
26 | Sleep 1
27 | $obj.Play()
28 | $ok = $true
29 | }
30 | }Until($ok -eq $true)
--------------------------------------------------------------------------------
/GetUptime.ps1:
--------------------------------------------------------------------------------
1 | #A *Nix-like uptime function, from student Timothy Kite
2 | function Get-Uptime {
3 | Param( $computer = "localhost" )
4 | $os = Get-WmiObject Win32_OperatingSystem -ComputerName $computer
5 | $uptime = (Get-Date) - $os.ConvertToDateTime($os.LastBootUpTime)
6 | $now = "$((Get-Date).Hour):$((Get-Date).Minute)"
7 | $users = Get-WmiObject Win32_ComputerSystem -ComputerName $computer | select Username | Measure-Object | select -ExpandProperty Count
8 | $loadAverage = Get-WmiObject win32_processor -ComputerName $computer | Measure-Object -Property LoadPercentage -Average |
9 | select -ExpandProperty Average
10 | return "[$now] System $computer up " + $uptime.Days + " days, " + $uptime.Hours + ":" + $uptime.Minutes + ", " +
11 | $users + " users, load average: " + $loadAverage
12 | }get-
--------------------------------------------------------------------------------
/DSC/Partial_Configs_Demo/1-LCM_Partial_Config_Setup.ps1:
--------------------------------------------------------------------------------
1 | [DSCLocalConfigurationManager()]
2 | configuration AdatumPartialConfig
3 | {
4 | Node localhost
5 | {
6 | Settings
7 | {
8 | RefreshMode = 'Push'
9 | ConfigurationMode = 'ApplyandAutoCorrect'
10 | }
11 | PartialConfiguration AdatumEnvVars
12 | {
13 | Description = 'Custom Adatum Environment variable'
14 | RefreshMode = 'Push'
15 | }
16 | PartialConfiguration AdatumRegistry
17 | {
18 | Description = 'Custom Adatum Registry entry'
19 | RefreshMode = 'Push'
20 | }
21 | }
22 | }
23 |
24 | AdatumPartialConfig
25 |
26 | Set-DscLocalConfigurationManager -Path '.\AdatumPartialConfig'
27 |
28 | Get-DscLocalConfigurationManager
--------------------------------------------------------------------------------
/Azure/EnumerateResourceTypeNamesByProviderPath.ps1:
--------------------------------------------------------------------------------
1 | # Look for Az module and, if present, load the equivalent -AzureRm aliases:
2 |
3 | If(Get-Module -ListAvailable Az.*){
4 | Enable-AzureRmAlias
5 | }
6 |
7 | # Check for Azure login:
8 |
9 | Try{
10 | Get-AzureRmContext -ErrorAction Stop
11 | }Catch{
12 | Add-AzureRmAccount
13 | }
14 | $results = @()
15 | Get-AzureRmResourceProvider | ForEach-Object {
16 | $resources = $_ | Select -ExpandProperty ResourceTypes | Select ResourceTypeName
17 | ForEach($resource in $resources){
18 | $properties = @{
19 | ResourceTypeName = "$($resource.ResourceTypeName)"
20 | ProviderPath = "$($_.ProviderNameSpace)/$($resource.ResourceTypeName)"
21 | }
22 | $results += New-Object -TypeName PSObject -Property $properties
23 | }
24 | }
25 | $results | Sort ResourceTypeName
--------------------------------------------------------------------------------
/DSC/AutomaticVariables.ps1:
--------------------------------------------------------------------------------
1 | $myData = @{
2 | AllNodes = @(
3 | @{
4 | NodeName = "StudentServer"
5 | EvaluationSoftware = @{
6 | Name = "Test Software"
7 | Version = "1.2.3"
8 | ProductID = '000000-11-222-3333333'
9 | }
10 | NewString = "NewString"
11 | }
12 | )
13 | }
14 |
15 | Configuration DataTest {
16 | Import-DscResource -ModuleName PSDesiredStateConfiguration
17 | Node $AllNodes.NodeName {
18 | File TestFile {
19 | Ensure = 'Present'
20 | DestinationPath = "C:\demo\$($Node.EvaluationSoftware.Name)"
21 | Contents = $Node.EvaluationSoftware.Version
22 | }
23 | }
24 | }
25 |
26 | DataTest -ConfigurationData $myData -Outputpath C:\Users\Administrator\DataTest
27 |
--------------------------------------------------------------------------------
/DSC/GroupResource.ps1:
--------------------------------------------------------------------------------
1 | Configuration GroupResource {
2 | Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
3 | Node $AllNodes.NodeName {
4 | Group GroupExample {
5 | GroupName = "ExampleGroup"
6 | Members = "Nicole", "Rocky", "Mark", "BlueBuffalo\Administrator"
7 | Credential = (Get-Credential)
8 |
9 | }
10 | }
11 | }
12 |
13 | $ConfigurationData = @{
14 | AllNodes = @(
15 | @{
16 | NodeName = "*"
17 | PSDscAllowPlainTextPassword = $true
18 | }
19 | @{
20 | NodeName = "StudentServer2"
21 | }
22 | )
23 | }
24 | Clear-Host
25 | GroupResource -OutputPath 'C:\DSC Resources\MOF\Group' -Verbose -ConfigurationData $ConfigurationData
26 |
27 | Start-DscConfiguration -Path 'C:\DSC Resources\MOF\Group\' -Wait -Verbose -Force
--------------------------------------------------------------------------------
/Networking/RestartDNS.ps1:
--------------------------------------------------------------------------------
1 | <# Assumes E:\dns.txt contains a server list in the following format:
2 |
3 | plant,server
4 | 1,ServerA
5 | 1,ServerB
6 | 2,ServerC
7 | 3,ServerD
8 | 3,ServerE
9 |
10 | etc.
11 | #>
12 | $list = Import-CSV "E:\dns.txt"
13 | $i = $null
14 | $numberOfPlants = 10
15 | $delayBetweenPlants = 300 # in seconds
16 | Do{
17 | $i++
18 | $plant = $list | Where-Object {$_.plant -eq $i}
19 | Write-Progress -Activity "Restarting DNS for Plant:" -Status $i -PercentComplete ($i/$numberOfPlants * 100)
20 | Write-Host "Plant $i" -ForegroundColor Yellow -BackgroundColor DarkCyan
21 | ForEach($server in $plant){
22 | $serverName = $server.server
23 | #Invoke-Command $serverName {Restart-Service DNS}
24 | Write-Host "Restarting DNS on $serverName"
25 | }
26 | Sleep $delayBetweenPlants
27 | }Until($i -ge $numberOfPlants)
28 |
29 |
--------------------------------------------------------------------------------
/Azure/Set_JIT_on_ResourceGroup.ps1:
--------------------------------------------------------------------------------
1 | If(! (Get-Module -ListAvailable Az.Security)){Install-Module Az.Security -Force}
2 | $resourceGroup = 'JIT-Test-RG'
3 | $location = (Get-AzResourceGroup $resourceGroup).Location
4 | $subscriptionID = (Get-AzSubscription).Id
5 | $vms = (Get-AzVm -ResourceGroupName $resourceGroup).Name
6 |
7 |
8 | ForEach($vm in $vms){
9 | $JitPolicy = @{
10 | id="/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Compute/virtualMachines/$vm"
11 | ports= @{
12 | number=3389
13 | protocol="*"
14 | allowedSourceAddressPrefix=@("*")
15 | maxRequestAccessDuration="PT3H"
16 | }
17 | }
18 | $JitPolicyArray = @($JitPolicy)
19 | Set-AzJitNetworkAccessPolicy -Kind 'Basic' -Location $location -Name $vm -ResourceGroupName $resourceGroup -VirtualMachine $JitPolicyArray
20 | }
--------------------------------------------------------------------------------
/GetWebSensor2.ps1:
--------------------------------------------------------------------------------
1 | Function Get-WebSensor {
2 | Param(
3 | $sourcePath = "http://bit.ly/1KzgLeX"
4 | )
5 | $web = New-Object System.Net.WebClient
6 | $statistics = $web.DownloadString($sourcePath).split("`n") |
7 | Select-String ''
8 | $statistics = $statistics -replace '(.*?)TF:', ""
9 | $statistics = $statistics -replace 'HU:', ","
10 | $statistics = $statistics -replace '%IL\s+', ","
11 | $statistics = $statistics -replace '\s+