├── 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 | [![Donate](./donate.png)](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 | image" -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+', "" 12 | $statistics = $statistics.Split(",") 13 | 14 | $statObject = New-Object PSObject 15 | $statObject | Add-Member NoteProperty "TempF" ([decimal]$statistics[0]) 16 | $statObject | Add-Member NoteProperty "Humidity" ([decimal]$statistics[1]) 17 | $statObject | Add-Member NoteProperty "Illumination" ([decimal]$statistics[2]) 18 | 19 | Write-Output $statObject 20 | } 21 | -------------------------------------------------------------------------------- /Networking/CurrentIP.ps1: -------------------------------------------------------------------------------- 1 | $sourcePath = "http://checkip.dyndns.org" 2 | $web = new-object system.net.webclient 3 | $raw = $web.DownloadString($sourcePath) 4 | $raw -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" | Out-Null 5 | $currentIP = $matches.values 6 | If(!(Test-Path "$($psscriptroot)\CurrentIP.txt")){ 7 | $currentIP | Out-File "$($psscriptroot)\CurrentIP.txt" 8 | Send-MailMessage -From "nobodaddy@nowhere.net" -To "stugart@gmail.com" -Subject "IP ADDRESS CHANGE" -SmtpServer 192.168.1.2 -Body $currentIP 9 | } 10 | Else{ 11 | If((Get-Content "$($psscriptroot)\CurrentIP.txt" | Select -first 1) -ne ($currentIP | Select -first 1)){ 12 | $currentIP | Out-File "$($psscriptroot)\CurrentIP.txt" -Force 13 | Send-MailMessage -From "nobodaddy@nowhere.net" -To "stugart@gmail.com" -Subject "IP ADDRESS CHANGE" -SmtpServer 192.168.1.2 -Body $currentIP 14 | } 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /GuessTheNumber.ps1: -------------------------------------------------------------------------------- 1 | Function Guess-TheNumber{ 2 | Param( 3 | [int]$upperRange = 100 4 | ) 5 | Clear-Host 6 | [int]$number = Get-Random -Minimum 1 -Maximum $upperRange 7 | $guesses = $null 8 | $allBelow = @(1) 9 | $allAbove = @($upperRange) 10 | Do 11 | { 12 | $guesses++ 13 | $floor = $allBelow | Sort-Object | Select-Object -Last 1 14 | $ceiling = $allAbove | Sort-Object | Select-Object -First 1 15 | [int]$guess = Read-Host "Guess the number between $floor and $ceiling" 16 | If([int]$guess -lt $number){ 17 | Write-Host "That's too low! Try again." -ForegroundColor Red 18 | $allBelow += $guess 19 | } 20 | ElseIf([int]$guess -gt $number){ 21 | Write-Host "That's too high! Try again." -ForegroundColor Red 22 | $allAbove += $guess 23 | } 24 | }Until($guess -eq $number) 25 | Write-Host "You got it! The number was $number. It took you $guesses guesses." -ForegroundColor Green 26 | } -------------------------------------------------------------------------------- /UnlockGeneticCode.ps1: -------------------------------------------------------------------------------- 1 | Function Decode-DNA{ 2 | Param( 3 | $block 4 | ) 5 | $Script:numberBlock = @() 6 | ForEach($char in $block){ 7 | Switch ($char){ 8 | "A" { 9 | $Script:numberBlock += 0 10 | Break 11 | } 12 | "C" { 13 | $Script:numberBlock += 1 14 | Break 15 | } 16 | "G" { 17 | $Script:numberBlock += 2 18 | Break 19 | } 20 | "T" { 21 | $Script:numberBlock += 3 22 | Break 23 | } 24 | } 25 | } 26 | } 27 | Function ExpandTo-ASCII{ 28 | Param( 29 | $DNANumbers 30 | ) 31 | $Script:ASCIINums += [char](($DNANumbers[0] * 64) + ($DNANumbers[1] * 16) ` 32 | + ($DNANumbers[2] * 4) + ($DNANumbers[3])) 33 | } 34 | $secret = Read-Host "Enter Code to Decode" 35 | $secret = $secret.Split() 36 | $ASCIINums = @() 37 | For($char = $null, $i = 0;$i -le ($secret.Count - 1);$i+=4){ 38 | $char = $secret[$i..($i+3)] 39 | Decode-DNA ($char) 40 | ExpandTo-ASCII ($numberBlock) 41 | } 42 | "$ASCIINums" -------------------------------------------------------------------------------- /DSC/ScriptResourceDemo.ps1: -------------------------------------------------------------------------------- 1 | Configuration ScriptDemoShowScript { 2 | Import-DscResource -ModuleName 'PSDesiredStateConfiguration' 3 | Node StudentServer2 { 4 | Script ScriptDemo { 5 | GetScript = { 6 | @{ 7 | GetScript = $GetScript 8 | SetScript = $SetScript 9 | TestScript = $TestScript 10 | Result = "TestScript" 11 | } 12 | } 13 | SetScript = { 14 | Write-Verbose "Sleeping for 45 Seconds" 15 | Start-Sleep 45 16 | Write-Verbose "Script Task Completed" 17 | } 18 | TestScript = { 19 | $False 20 | } 21 | } 22 | } 23 | } 24 | 25 | ScriptDemoShowScript -OutputPath 'C:\DSC Resources\ScriptDemo' 26 | Start-DscConfiguration -Path 'C:\DSC Resources\ScriptDemo' -Verbose -Wait -------------------------------------------------------------------------------- /ActiveDirectory/AdminOSReport.ps1: -------------------------------------------------------------------------------- 1 | $ComputerList = “slasher”,“zombie”,"XPS" 2 | 3 | [Array]$AuditOSinfo = ` 4 | ForEach($ComputerName in $ComputerList) 5 | { 6 | $SavedAuditOS = get-wmiobject -Class Win32_OperatingSystem ` 7 | -ComputerName $ComputerName 8 | $SavedAuditIPAddr = Get-WmiObject -query ` 9 | "SELECT * FROM Win32_PingStatus WHERE Address = '$ComputerName'" 10 | $MyPSObject = New-Object PSObject -Property @{ 11 | ComputerName = $SavedAuditOS.csname 12 | IPv4Address = $SavedAuditIPAddr.IPv4Address 13 | IPStatusCode = $SavedAuditIPAddr.StatusCode 14 | SerialNumber = $SavedAuditOS.SerialNumber 15 | OSversion = $SavedAuditOS.Version 16 | SystemDescrip = $SavedAuditOS.Description 17 | OSName = $SavedAuditOS.Name.Split("|")[0] 18 | } 19 | $MyPSObject 20 | } 21 | 22 | $AuditOSinfo | Export-CSV -Path C:\temp\TestReport.csv -NoTypeInformation 23 | ii C:\temp\TestReport.csv 24 | -------------------------------------------------------------------------------- /WeatherDemo.ps1: -------------------------------------------------------------------------------- 1 | #Weather demo 2 | #Your API key at openweathermap.org is fe5c2a60e7255b20b113c52187629653 3 | #The free api key only permits querying once every 10 minutes... 4 | #Can download city ID codes here: http://bulk.openweathermap.org/sample/ 5 | #To convert Kelvin to Fahrenheit: 6 | # TempKelvin * 9/5 - 459.67 7 | $littletonCityID = 5429032 8 | $apiKey = 'fe5c2a60e7255b20b113c52187629653' 9 | # By city name: 10 | #$uri = "api.openweathermap.org/data/2.5/weather?q=Denver,us&mode=json&APPID=$apiKey" 11 | 12 | # By city ID: 13 | $uri = "api.openweathermap.org/data/2.5/weather?id=$littletonCityID&mode=json&APPID=$apiKey" 14 | 15 | # Forecast by city ID: 16 | $forecastURI = "api.openweathermap.org/data/2.5/forecast?id=$littletonCityID&mode=json&APPID=$apiKey" 17 | $results = Invoke-RestMethod $uri 18 | # or 19 | #$results = Invoke-WebRequest $forecastURI 20 | 21 | Function ConvertFrom-Kelvin { 22 | Param( 23 | [double]$temp 24 | ) 25 | ($temp -273.15) * 9/5 + 32 26 | } -------------------------------------------------------------------------------- /Set-Color.ps1: -------------------------------------------------------------------------------- 1 | # Set-Color.ps1 2 | # Written by Bill Stewart (bill.stewart@frenchmortuary.com) 3 | 4 | param([String] $Color = $(throw "Please specify a color.")) 5 | 6 | # Trap the error and exit the script if the user 7 | # specified an invalid parameter. 8 | trap [System.Management.Automation.RuntimeException] { 9 | write-error -errorrecord $ERROR[0] 10 | exit 11 | } 12 | 13 | # Assume -color specifies a hex value and it cast to a [Byte]. 14 | $newcolor = [Byte] ("0x{0}" -f $Color) 15 | 16 | # Split the color into background and foreground colors. 17 | # [Math]::Truncate returns a [Double], so cast it to an [Int]. 18 | $bg = [Int] [Math]::Truncate($newcolor / 0x10) 19 | $fg = $newcolor -band 0xF 20 | 21 | # If the background and foreground match, throw an error; 22 | # otherwise, set the colors. 23 | if ($bg -eq $fg) { 24 | write-error "The background and foreground colors must not match." 25 | } else { 26 | $HOST.UI.RawUI.BackgroundColor = $bg 27 | $HOST.UI.RawUI.ForegroundColor = $fg 28 | } 29 | -------------------------------------------------------------------------------- /GetLetterFrequency.ps1: -------------------------------------------------------------------------------- 1 | Function Get-Frequency { 2 | # A function to do a basic alphabetic letter frequency count on a piece of text 3 | Param( 4 | [Parameter(Mandatory=$true)] 5 | [string]$string 6 | ) 7 | [string]$string = $string -replace"\W","" # Remove non-word characters from the string 8 | [string]$string = $string -replace"\d","" # Remove digits from the string 9 | [string]$string = $string.ToLower() # Convert string to lower case 10 | [int]$TotalChars = $string.Length 11 | ForEach($letter in 97..122){ 12 | [char]$letter = $letter 13 | [int]$letterTotalChars = ($string.Replace("$letter","")).Length 14 | $properties = @{ 15 | "Letter" = $letter 16 | "Number of Occurences" = ($TotalChars - $letterTotalChars) 17 | "Frequency %" = [math]::Round((($TotalChars - $letterTotalChars)/ $TotalChars) * 100,2) 18 | } 19 | New-Object -TypeName PSObject -Property $properties 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /DiffieHelmanExchangeExample.ps1: -------------------------------------------------------------------------------- 1 | [int]$iG = Read-Host "Enter a prime number" 2 | [int]$iP = Read-Host "Enter another prime number GREATER than $iG" 3 | 4 | # Note: the random number needs to be very small here, or 5 | # "Not a Number" (NaN) errors will result in PowerShell 6 | 7 | $iXa = Read-Host "Enter a random number. Keep this secret, Student1" 8 | $iXb = Read-Host "Enter a random number. Keep this secret, Student2" 9 | 10 | $iYa = ([math]::Pow($iG,$iXa)) % $iP 11 | $iYb = ([math]::Pow($iG,$iXb)) % $iP 12 | 13 | Write-Host "Student1 Ya = $iYa `n`nOpenly exchange this number with Student2." 14 | Write-Host "Student2 Yb = $iYb `n`nOpenly exchange this number with Student1." 15 | 16 | Write-Host "Now you can compute your secret key.`n" 17 | Write-Host "Student1 key formula is (Yb^Xa) Mod P `n`t`t = " ([math]::Pow($iYb,$iXa)) % $iP "`n`t`t = " (([math]::Pow($iYb,$iXa)) % $iP) 18 | Write-Host "Student2 key formula is (Ya^Xb) Mod P `n`t`t = " ([math]::Pow($iYa,$iXb)) % $iP "`n`t`t = " (([math]::Pow($iYa,$iXb)) % $iP) -------------------------------------------------------------------------------- /DSC/UserResource.ps1: -------------------------------------------------------------------------------- 1 | Configuration UserResource { 2 | Param ( 3 | $password 4 | ) 5 | Import-DscResource -ModuleName 'PSDesiredStateConfiguration' 6 | Node StudentServer2 { 7 | User UserResourceExample { 8 | Ensure = 'Present' 9 | UserName = 'Bob' 10 | Password = $password 11 | #DependsOn = "[Group]GroupExample" 12 | } 13 | } 14 | } 15 | 16 | $configData = @{ 17 | AllNodes = @( 18 | @{ 19 | NodeName = 'StudentServer2' # cannot be an asterisk unless 1 or more additional NodeName hash tables for specific nodes are added 20 | PSDscAllowPlainTextPassword = $true 21 | } 22 | ) 23 | } 24 | 25 | UserResource -OutputPath 'C:\DSC Resources\MOF\User\' -ConfigurationData $configData -password ` 26 | (Get-Credential -UserName "Bob" -Message "Enter the password for the new user") 27 | Start-DscConfiguration -Path 'C:\DSC Resources\MOF\User\' -Wait -Verbose -Force 28 | -------------------------------------------------------------------------------- /PrivateWorkingSet.ps1: -------------------------------------------------------------------------------- 1 | Function Get-PrivateBytes { 2 | $i = 0 3 | $total = 0 4 | $procs = Get-Process 5 | $count = $procs.Count 6 | ForEach($processName in (Get-Process)){ 7 | $i++ 8 | $percent = [math]::Round($i/$count * 100) 9 | $privateBytes = get-counter -counter "\Process($($processName.name))\Private Bytes" -ErrorAction SilentlyContinue | 10 | select -expandproperty countersamples | select -expandproperty cookedvalue 11 | $total = $total + $privateBytes 12 | $running = "{0:N0} K" -f ($total/1KB) 13 | Write-Progress -Activity "Collecting Private Working Set info" -PercentComplete $percent -Status "Commit Size : $running" -CurrentOperation "$percent% complete" 14 | "$($processName.name) - {0:N0} K" -f ($privateBytes/1KB) 15 | } 16 | Write-Progress -Activity "Collecting Private Working Set info" -Completed 17 | $total = "`nTotal : {0:N2}GB" -f ($total/1GB) 18 | Write-Host $total -ForegroundColor DarkCyan -BackgroundColor DarkRed 19 | } -------------------------------------------------------------------------------- /RenAdmin.ps1: -------------------------------------------------------------------------------- 1 | Function Rename-Admin { 2 | [CmdletBinding()] 3 | Param( 4 | [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] 5 | [string[]]$computerName = 'localhost', 6 | 7 | [Parameter(Mandatory=$true)] 8 | [string]$newName 9 | ) 10 | Process{ 11 | ForEach($computer in $computerName){ 12 | $admin = Get-WmiObject -ComputerName $computer -Query "Select * From Win32_UserAccount Where LocalAccount = TRUE AND SID LIKE 'S-1-5%-500'" 13 | $admin.Rename($newName) | Out-Null 14 | } 15 | } 16 | } 17 | 18 | <# 19 | $comp = "LON-CL1" 20 | Write-Host "Old name is " (Get-WmiObject -ComputerName $comp -Query "Select * From Win32_UserAccount Where LocalAccount = TRUE AND SID LIKE 'S-1-5%-500'").Name 21 | Rename-Admin -newName Bigfoot -computerName $comp 22 | Write-Host "New name is " (Get-WmiObject -ComputerName $comp -Query "Select * From Win32_UserAccount Where LocalAccount = TRUE AND SID LIKE 'S-1-5%-500'").Name 23 | #> -------------------------------------------------------------------------------- /Azure/MapAzureFileShare.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | Map a drive from a Windows machine to an Azure file share 4 | 5 | Requirements: 6 | 7 | From outside of Azure: Windows 8/Server 2012 or later 8 | From within Azure: Windows 7/Server 2008R2 or later 9 | 10 | #> 11 | Function Map-AzureDrive{ 12 | Param( 13 | [Parameter(Mandatory=$true)] 14 | [string]$acctKey, 15 | 16 | [Parameter(Mandatory=$true)] 17 | [string]$storageAcctName, 18 | 19 | [Parameter(Mandatory=$true)] 20 | [string]$shareName, 21 | 22 | [string]$driveLetter = 'Z', 23 | 24 | [switch]$hideInExplorer 25 | ) 26 | $secureKey = ConvertTo-SecureString -String $acctKey -AsPlainText -Force 27 | $credential = New-Object System.Management.Automation.PSCredential -ArgumentList "Azure\$storageAcctName", $secureKey 28 | If($hideInExplorer){ 29 | $reconnect = $false 30 | } 31 | New-PSDrive -Name $driveLetter -PSProvider FileSystem ` 32 | -Root "\\$storageAcctName.file.core.windows.net\$shareName" ` 33 | -Credential $credential -Persist:$reconnect -Scope Global 34 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Shawn Stugart 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Azure/GetAllAzureVmExtensions.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [Parameter(Mandatory=$true)] 3 | [string]$location 4 | ) 5 | 6 | # Check for Azure login: 7 | 8 | Try{ 9 | Get-AzContext -ErrorAction Stop | Out-Null 10 | }Catch{ 11 | Add-AzAccount 12 | } 13 | 14 | $publishers = Get-AzVmImagePublisher -Location $location | Select-Object -ExpandProperty PublisherName 15 | $publisherCount = $publishers.Count 16 | $count = 0 17 | ForEach($publisher in $publishers){ 18 | $count++ 19 | Write-Progress -Activity 'Enumerating Publisher:' -Status $publisher -PercentComplete ($count/$publisherCount * 100) 20 | $types = Get-AzVmExtensionImageType -Location $location -PublisherName $publisher | Select-Object -ExpandProperty Type 21 | ForEach($type in $types){ 22 | If(Get-AzVMExtensionImage -Location $location -PublisherName $publisher -Type $type -ErrorAction SilentlyContinue){ 23 | $properties = @{ 24 | 'Publisher' = $publisher 25 | 'Type' = $type 26 | } 27 | $object = New-Object -TypeName PSObject -Property $properties 28 | Write-Output $object 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Azure/GetAzureVmExtensions.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 | 15 | # Build an Out-Gridview pipeline for display of available VM extensions: 16 | 17 | $location = Get-AzureRmLocation | Out-GridView -OutputMode Single -Title "SELECT A LOCATION AND CLICK OK" | Select-Object -ExpandProperty Location 18 | $publisher = Get-AzureRmVMImagePublisher -Location $location | Out-GridView -OutputMode Single -Title "SELECT A PUBLISHER AND CLICK OK" | Select-Object -ExpandProperty PublisherName 19 | $type = Get-AzureRmVMExtensionImageType -Location $location -PublisherName $publisher | Out-GridView -OutputMode Single -Title "SELECT A TYPE AND CLICK OK" | Select-Object -ExpandProperty Type 20 | Try { 21 | Get-AzVMExtensionImage -Location $location -PublisherName $publisher -Type $type -ErrorAction Stop 22 | }Catch { 23 | Write-Host "No extensions types for publisher $publisher in $location" -ForegroundColor DarkCyan -BackgroundColor DarkRed 24 | } 25 | -------------------------------------------------------------------------------- /GetCalendar.ps1: -------------------------------------------------------------------------------- 1 | Function Get-Calendar { 2 | [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null 3 | [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null 4 | 5 | $form = New-Object Windows.Forms.Form 6 | $form.Text = "Select the date ranges from the Calendar and press Enter" 7 | $form.Size = New-Object Drawing.Size @(656,639) 8 | 9 | # Create a "hidden" SelectButton to handle Enter Key 10 | 11 | $btnSelect = New-Object System.Windows.Forms.Button 12 | $btnSelect.Size = "1,1" 13 | $btnSelect.add_Click({ 14 | $form.Close() 15 | }) 16 | $form.Controls.Add($btnSelect ) 17 | $form.AcceptButton = $btnSelect 18 | 19 | # Add Calendar 20 | 21 | $calendar = New-Object System.Windows.Forms.MonthCalendar 22 | $calendar.ShowWeekNumbers = $false 23 | $calendar.MaxSelectionCount = 356 24 | $calendar.Dock = 'Fill' 25 | $form.Controls.Add($calendar) 26 | 27 | # Display the form 28 | 29 | $form.Add_Shown({$form.Activate()}) 30 | [void]$form.Showdialog() 31 | 32 | # Return Start and End date 33 | 34 | Return $calendar.SelectionRange 35 | 36 | } -------------------------------------------------------------------------------- /ActiveDirectory/ADStuff.ps1: -------------------------------------------------------------------------------- 1 | $root = [ADSI]"" 2 | $domain = $root.distinguishedName 3 | $binding = [ADSI]"LDAP://$domain" 4 | $OU = Read-Host "Enter the OU Name" 5 | $newOU = $binding.Create("OrganizationalUnit", "OU=$OU") 6 | $newOU.SetInfo() 7 | $userFirstName = Read-Host "Enter User's First Name" 8 | $userLastName = Read-Host "Enter User's Last Name" 9 | $userUPN = Read-Host "Enter User's UPN Logon" 10 | $userPass = Read-Host -AsSecureString "Enter User's Password" 11 | $global = Read-Host "Enter Name for Global Group" 12 | $local = Read-Host "Enter Name for Local Group" 13 | $user = $newOU.Create("user", "CN=$userFirstName $userLastName") 14 | $user.Put("sAMAccountName", $userFirstName) 15 | $user.Put("givenName", $userFirstName) 16 | $user.Put("sn", $userLastName) 17 | $user.Put("userPrincipalName", $userUPN) 18 | $user.SetInfo() 19 | $user.psbase.Invoke("SetPassword", "$userPass") 20 | $user.psbase.CommitChanges() 21 | $newGlobal = $newOU.Create("group","CN=GG_$global") 22 | $newGlobal.SetInfo() 23 | $newLocal = $newOU.Create("group","CN=DLG_$local") 24 | $newLocal.Put("groupType", "-2147483644") 25 | $newLocal.SetInfo() 26 | $newGlobal.add("LDAP://"+$user.distinguishedname) 27 | $newLocal.add("LDAP://"+$newGlobal.distinguishedname) -------------------------------------------------------------------------------- /Azure/GetAzureImages.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 | 15 | # Build an Out-Gridview pipeline for selection of an Azure Marketplace VM image: 16 | 17 | $location = Get-AzureRmLocation | Out-GridView -OutputMode Single -Title "SELECT A LOCATION AND CLICK OK" | Select -ExpandProperty Location 18 | $publisher = Get-AzureRmVMImagePublisher -Location $location | Out-GridView -OutputMode Single -Title "SELECT A PUBLISHER AND CLICK OK" | Select -ExpandProperty PublisherName 19 | $offer = Get-AzureRmVMImageOffer -Location $location -PublisherName $publisher | Out-GridView -OutputMode Single -Title "SELECT AN OFFER AND CLICK OK" | Select -ExpandProperty Offer 20 | $sku = Get-AzureRmVMImageSKU -Location $location -PublisherName $publisher -Offer $offer | 21 | Out-GridView -OutputMode Single -Title "SELECT AN SKU AND CLICK OK" | Select -ExpandProperty SKUs 22 | Get-AzureRmVMImage -Location $location -PublisherName $publisher -Offer $offer -Skus $sku | Out-Gridview -OutputMode Single -Title "SELECT AN IMAGE and CLICK OK" -------------------------------------------------------------------------------- /DicewarePassword.ps1: -------------------------------------------------------------------------------- 1 | Function Get-DiceWarePassword { 2 | Param( 3 | $filePath = 'https://raw.githubusercontent.com/simplescripter/PowerShell-Depot/master/DicewarePasswordWordlist.txt', #$filepath is a local path or URL 4 | $numberOfWords = 5 5 | ) 6 | If ($filepath -match '^http'){ 7 | $wordList = (Invoke-WebRequest $filePath).Content | ConvertFrom-Csv -Delimiter "`t" -Header 'Number','Value' 8 | }Else{ 9 | $wordList = Import-CSV -Delimiter "`t" -Path $filePath -Header 'Number','Value' 10 | } 11 | $hashList = @{} 12 | 13 | # Create a hash table of diceware words 14 | ForEach ($word in $wordList){ 15 | $hashList.Add($word.Number,$word.Value) 16 | } 17 | 18 | 19 | $password = @() 20 | For ($i = 1; $i -le $numberOfWords; $i++){ 21 | $randomNumber = @() 22 | 23 | # Simulate rolling a single die 5 times and join the values into an integer 24 | 25 | For ($j = 1; $j -le 5; $j++){ 26 | $randomNumber += Get-Random -Minimum 1 -Maximum 6 27 | } 28 | $randomNumber = $randomNumber -join '' 29 | 30 | #Look up the 5-digit number in hash table and add it to our password 31 | $password += $hashList."$randomNumber" 32 | } 33 | $password = $password -join " " 34 | Write-Output $password 35 | } -------------------------------------------------------------------------------- /StartContinousPing.ps1: -------------------------------------------------------------------------------- 1 | Function Start-ContinuousPing { 2 | Param( 3 | [string]$nameOrIP, 4 | [int]$interval = 5 5 | ) 6 | $key = $null 7 | $global:ProgressPreference = 'SilentlyContinue' 8 | 9 | If($PSBoundParameters.Keys -contains 'nameOrIP'){ 10 | Write-Host "Pinging $nameOrIP every $interval seconds. Hit any key to quit." -BackgroundColor White -ForegroundColor DarkMagenta 11 | }else{ 12 | Write-Host "Pinging internetbeacon.msedge.net every $interval seconds. Hit any key to quit." -BackgroundColor White -ForegroundColor DarkMagenta 13 | } 14 | Do{ 15 | $timeStamp = (Get-Date).ToLongTimeString() 16 | If($PSBoundParameters.Keys -contains 'nameOrIP'){ 17 | $result = Test-NetConnection $nameOrIP -WarningAction SilentlyContinue 18 | }else{ 19 | $result = Test-NetConnection -WarningAction SilentlyContinue 20 | } 21 | Write-Host "$timeStamp : Ping success: $($result.PingSucceeded)" 22 | Start-Sleep $interval 23 | while([console]::KeyAvailable){ 24 | $key = [console]::Readkey("NoEcho").Key 25 | } 26 | }Until($key) 27 | Write-Host "Key pressed. Quitting" -ForegroundColor DarkRed -BackgroundColor White 28 | $global:ProgressPreference = 'Continue' 29 | } 30 | 31 | Start-ContinuousPing -nameOrIP 8.8.8.8 -interval 3 -------------------------------------------------------------------------------- /DetectUSB.ps1: -------------------------------------------------------------------------------- 1 | $computerName = $env:COMPUTERNAME 2 | $nameSpace = 'root\subscription' 3 | $logPath = 'C:\USB\USB.log' 4 | #Filter 5 | $wmiArguments = @{ 6 | Name = 'USBFilter' 7 | EventNameSpace = 'root\CIMV2' 8 | QueryLanguage = 'WQL' 9 | Query = "SELECT * FROM __InstanceModificationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk AND TargetInstance.DriveType=2'" 10 | } 11 | $filter = Set-WMIInstance -Class __EventFilter -ComputerName $computerName -Namespace $nameSpace -Arguments $wmiArguments 12 | 13 | ##Consumer 14 | $wmiArguments = @{ 15 | Name = 'USBConsumer' 16 | FileName = $logPath 17 | # The Text parameter of LogFileEventConsumer accepts only literal strings and WMI TargetInstance properties; 18 | # PowerShell variables or other dynamic sources of information are not "dynamic" in the Text string 19 | # You could use the CommandLineEventConsumer with a script to write the information instead 20 | Text = "[USB] Device id %TargetInstance.DeviceID%" 21 | } 22 | $consumer = Set-WmiInstance -Class LogFileEventConsumer -ComputerName $computerName -Namespace $nameSpace -Arguments $wmiArguments 23 | 24 | #Binding 25 | $wmiArguments = @{ 26 | Filter = $filter 27 | Consumer = $consumer 28 | } 29 | $binding = Set-WmiInstance -Class __FilterToConsumerBinding -ComputerName $computerName -Namespace $nameSpace -Arguments $wmiArguments 30 | -------------------------------------------------------------------------------- /GetQuote.ps1: -------------------------------------------------------------------------------- 1 | Function Get-Quote { 2 | Param( 3 | $uri = 'http://www.quotationspage.com/qotd.html', 4 | [ValidateRange(1,4)] 5 | [int]$numberOfQuotes = 4 6 | ) 7 | 8 | #$today = (Get-Date).GetDateTimeFormats()[8] # Get current date in "Month Day, Year" format 9 | $page = Invoke-WebRequest $uri 10 | 11 | #As an alternative to the following approach, consider using multi-line regex mode modifier as seen here: 12 | # https://www.apharmony.com/software-sagacity/2014/08/multi-line-regular-expression-replace-in-powershell/ 13 | $anchorString = 'Michael Moncur' 14 | $quote = $page.Content.Split("`n") | Select-String $anchorString -Context 0,7 15 | $quote = $quote -replace '> ','' 16 | $quote = $quote -replace ' .*"/quotes/\w+/">',' ' 17 | $quote = $quote -replace '.*class="author".*"/quotes/[\w\.]+/">',' ' 18 | $quote = $quote -replace '.*class="quote".*html">','' 19 | $quote = $quote -replace '','' 20 | $quote = $quote -replace ' .*>','' 21 | $quote = $quote -replace '','' 22 | $quote = $quote -replace '','' 23 | $quote = $quote -replace '\n\s*\n',"`n" 24 | $quote = $quote -replace '
','' 25 | $quote = $quote -split "`n" | Select -Skip 1 26 | For($i=0;$i -le $numberOfQuotes - 1;$i++){ 27 | Write-Output $quote[$i] `n 28 | } 29 | } -------------------------------------------------------------------------------- /DupeFiles.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | $dir = (Get-Location), 3 | $moveOrdelete = "move", #use "move" or "delete" 4 | $moveDir = "C:\Users\Shawn.Elysium\Desktop\50331 to Delete\dupes", # path to a directory to store duplicates when moving 5 | $maxFiles = 100 #maximum number of file duplicates to move or delete 6 | ) 7 | If($moveOrdelete -eq "move"){ 8 | If(-not (Test-Path $moveDir)){ 9 | Throw "Directory $moveDir does not exist. Exiting." 10 | Break 11 | } 12 | $dupeFiles = Get-ChildItem $dir -Recurse | 13 | Group-Object Name, Length, LastWriteTime | 14 | Where-Object {$_.Count -gt 1} 15 | ForEach($fileName in $dupeFiles){ 16 | ForEach($file in $fileName.Group[1..$maxFiles]){Write-Host -ForegroundColor Green "Moving" $file.FullName "to $moveDir"} 17 | if($fileName.Count -eq 2){ 18 | ForEach-Object{$fileName.Group[1..$maxFiles]} | 19 | Move-Item -Destination $moveDir} 20 | else{ 21 | $dupes = $fileName.Group[1..$maxFiles] 22 | ForEach($duplicate in $dupes){ 23 | Move-Item -Path $duplicate.Fullname -Destination (("$movedir\" + $duplicate.Name) + "_" + (Get-Random)) 24 | } 25 | } 26 | } 27 | } 28 | Else{ 29 | $dupeFiles = Get-ChildItem $dir -Recurse | 30 | Group-Object Name, Length, LastWriteTime | 31 | Where-Object {$_.Count -gt 1} 32 | ForEach($file in $dupeFiles){ 33 | Write-Host -ForeGroundColor Green "Deleting" $file.group[0] 34 | $file.Group[1..$maxFiles] | 35 | Remove-Item} 36 | } -------------------------------------------------------------------------------- /BirthdayParadoxExample.ps1: -------------------------------------------------------------------------------- 1 | # A demonstration of the 'Birthday Paradox,' wherein a 50% probability exists that 2 | # any two random people will share the same birthday within a group of 23. 3 | # By the time the group size reaches 60, there is over a 99% probability that 2 people 4 | # will share the same birthday 5 | 6 | $start = Get-Date "1/1/2016" # 2016 was a leap year, so we'll use it to get all possible birthdays 7 | Remove-Variable daysOfYear -ErrorAction SilentlyContinue 8 | # Using a .NET arraylist because it's faster than a fixed array... 9 | $daysOfYear = New-Object System.Collections.ArrayList 10 | For($i = 0; $i -le 366;$i++){ 11 | $daysOfYear.add((Get-Date ($start.AddDays($i)) -Format 'MMMM dd')) | Out-Null 12 | } 13 | # ...but Get-Random doesn't seem to like picking from an arraylist, so 14 | # convert it to a standard array. Which requires deleting the $daysOfYear variable 15 | # at the beginning of the script 16 | 17 | [array]$daysOfYear = $daysOfYear 18 | $quit = $false 19 | $birthdays = @() 20 | $runningTotal = 0 21 | Do{ 22 | $runningTotal ++ 23 | $birthday = Get-Random $daysOfYear 24 | Write-Host $runningTotal -NoNewline -ForegroundColor DarkCyan 25 | Write-Host " $birthday" 26 | If($birthdays -contains $birthday){$quit = $true} 27 | $birthdays += $birthday 28 | }Until($quit) 29 | Write-Host "`n$runningTotal people before birthday collision" -ForegroundColor DarkCyan 30 | -------------------------------------------------------------------------------- /MenuExample.ps1: -------------------------------------------------------------------------------- 1 | 2 | $menu = @" 3 | ************************************************************************** 4 | Make a selection 5 | 6 | p = Display processes consuming the most memory 7 | o = Display processes by manufacturer 8 | s = Display running services 9 | h = Display installed hotfixes 10 | x = Exit this menu 11 | 12 | ************************************************************************** 13 | 14 | 15 | "@ 16 | 17 | Do{ 18 | cmd /c color 71 19 | $selection = Read-Host -Prompt $menu 20 | Clear-Host 21 | Switch ($selection){ 22 | p { 23 | Get-Process | Sort-Object WS -Descending | Select-Object -first 10 | Format-Table 24 | pause 25 | } 26 | o { 27 | Get-Process | Sort-Object Company | Format-Table -GroupBy Company 28 | pause 29 | } 30 | s { 31 | Get-Service | Where-Object Status -eq Running | Format-Table 32 | pause 33 | } 34 | h { 35 | Get-HotFix | Format-Table HotfixID,InstalledOn -AutoSize 36 | pause 37 | } 38 | Default { 39 | Write-Host "That is not a valid selection. Try again." -ForegroundColor DarkGray -BackgroundColor DarkRed 40 | } 41 | } 42 | }Until ($selection -eq "x") 43 | Switch ($PSVersionTable.PSEdition){ 44 | 'Core' {cmd /c color 07} 45 | 'Desktop' {cmd /c color 56} 46 | Default {cmd /c color 56} 47 | } 48 | Clear-Host 49 | -------------------------------------------------------------------------------- /ErrorHandlingDemo.ps1: -------------------------------------------------------------------------------- 1 | Param([string[]]$computers) 2 | 3 | Function A{ 4 | Param([string[]]$computers) 5 | foreach($computer in $computers){ 6 | Try{ 7 | gwmi Win32_BIOS -ComputerName $computer -ErrorAction Stop -ErrorVariable FunctionA_Error | FT SerialNumber,__SERVER 8 | }Catch{ 9 | Write-Warning "Error on $computer in FunctionA" 10 | Write-Host "********************************************************************************" 11 | Write-Warning $_.Exception.GetType().FullName 12 | Write-Warning $_.Exception.Message 13 | Write-Host "********************************************************************************" 14 | Write-Warning "FunctionA_Error variable contains $FunctionA_Error" 15 | Write-Host "********************************************************************************" 16 | Write-Warning "Error variable contains $($error[0])" 17 | } 18 | } 19 | } 20 | 21 | Function B{ 22 | Param([string[]]$computers) 23 | foreach($computer in $computers){ 24 | Try{ 25 | gwmi Win32_ComputerSystem -ComputerName $computer -ErrorAction Stop | FT Manufacturer,__SERVER 26 | }Catch{ 27 | Write-Warning "Error on $computer in FunctionB" 28 | Write-Warning $_.Exception 29 | Write-Warning $_.Exception.Message 30 | } 31 | } 32 | } 33 | 34 | A -computers Slasher,Dasher,Slasher 35 | #B -computers Slasher,Dasher,Slasher -------------------------------------------------------------------------------- /LogonNotification.ps1: -------------------------------------------------------------------------------- 1 | # Code to monitor logons on a set of computers. The code takes as input one or more computer names, 2 | # then registers a WMI event for each computer. It monitors changes to the Win32_ComputerSystem 3 | # class. When a user logs on, the class is modified, and the script reports who just logged on, 4 | # when and where. The ForEach loop is required because the -ComputerName parameter of the Register-WMIEvent 5 | # class does not support multiple values, so instead of a single event subscription being registered asynchronously (like 6 | # in VBScript, for example), you need to register multiple event subscriptions. 7 | 8 | $i = 0 # we need unique -SourceIdentifier parameters for each event subscription, so we'll use a counter 9 | "LON-CLI1", "LON-SVR1", "LON-SVR2" | # There are lots of other ways we could pipe computer names in 10 | ForEach-Object { 11 | If(Test-Connection -ComputerName $_ -Count 1 -Quiet){ 12 | $i++ 13 | Register-WmiEvent -Query "Select * From __instanceModificationEvent within 5 Where 14 | targetinstance isa 'Win32_ComputerSystem'" ` 15 | -ComputerName $_ ` 16 | -SourceIdentifier "LogonMon$i" ` 17 | -Action { 18 | If($user = $Event.SourceEventArgs.NewEvent.TargetInstance.UserName){ 19 | $machine = $Event.SourceEventArgs.NewEvent.TargetInstance.__SERVER 20 | Write-Host "$(Get-Date) $user Logged on to $machine" -ForegroundColor Green 21 | "$(Get-Date) $user Logged on to $machine" | Out-File "C:\logons.txt" -append 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /RetrieveAppEvents.ps1: -------------------------------------------------------------------------------- 1 | # RetrieveAppEvents.ps1; 3/14/07 2 | 3 | # BEGIN CALLOUT A 4 | # BEGIN COMMENT 5 | # Calculate datetime for one day earlier than current datetime 6 | # END COMMENT 7 | $date = (get-date).addDays(-1) 8 | # END CALLOUT A 9 | 10 | # BEGIN CALLOUT B 11 | # BEGIN COMMENT 12 | # Create a function to format the entry types 13 | # END COMMENT 14 | function FormatEntryType ($file) 15 | { 16 | # BEGIN COMMENT 17 | # Retrieve content from AppEvents.txt file 18 | # Replace the error and warning entry types 19 | # Output changes to new file 20 | # END COMMENT 21 | get-content $file | 22 | foreach-object { $_ -replace "error", "*** ERROR ***" } | 23 | foreach-object { $_ -replace "warning", "* Warning *" } | 24 | out-file -filePath c:\scripts\AppEvents_EntryTypes.txt 25 | } 26 | # END CALLOUT B 27 | 28 | # BEGIN CALLOUT C 29 | # BEGIN COMMENT 30 | # Retrieve application events for the last day 31 | # END COMMENT 32 | $events = get-eventlog application | where-object {$_.timeGenerated -gt $date} 33 | # END CALLOUT C 34 | 35 | # BEGIN CALLOUT D 36 | # BEGIN COMMENT 37 | # Output the application events to the AppEvents.txt file 38 | # Record only the time of the event, the entry type, the source, and the message 39 | # END COMMENT 40 | $events | foreach-object { out-file -filePath c:\scripts\AppEvents.txt -append ` 41 | -inputObject $_.timeGenerated, $_.entryType, $_.source, $_.message } 42 | # END CALLOUT D 43 | 44 | # BEGIN CALLOUT E 45 | # BEGIN COMMENT 46 | # Run the FormatEntryType function on the AppEvents.txt file 47 | # END COMMENT 48 | FormatEntryType c:\scripts\AppEvents.txt 49 | # END CALLOUT E 50 | -------------------------------------------------------------------------------- /GeneticCode.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | A fun exercise in making up a secret code based on the DNA bases ATCG 3 | Of course, close inspection reveals "illegal" base pairs in the secret code (biologically, cytosine always pairs with guanine, 4 | and adenine always pairs with thymine). 5 | 6 | The system uses a base-4 model for performing the switch. With base-4 math, we can use 4 "digits" to produce 256 7 | unique values. For example: 8 | 9 | Base-4: 1101 10 | Decimal (base-10): 81 11 | 1*(4^3) + 1*(4^2) + 0*(4^1) + 1*(4^0) = 64 + 16 + 0 + 1 = 81 12 | ASCII character 81 = Q 13 | 14 | So, encoding the base-4 number "1101" using ConvertTo-DNA, we get "CCAC" 15 | 16 | #> 17 | Function ConvertTo-DNA{ 18 | Param( 19 | $number 20 | ) 21 | Switch ($number){ 22 | "0"{ 23 | $Script:DNA += "A" 24 | Break 25 | } 26 | "1"{ 27 | $Script:DNA += "C" 28 | Break 29 | } 30 | "2"{ 31 | $Script:DNA += "G" 32 | Break 33 | } 34 | "3"{ 35 | $Script:DNA += "T" 36 | Break 37 | } 38 | } 39 | } 40 | 41 | Function ConvertTo-Quad{ 42 | Param( 43 | [int]$number 44 | ) 45 | $decimal = $number 46 | $binary = @() 47 | Do{ 48 | $binary += ($decimal % 4) 49 | $decimal /=4 50 | $decimal = [Math]::Floor($decimal) 51 | } While ($decimal -ge 1) 52 | [array]::Reverse($binary) 53 | ForEach($char in $binary){ 54 | ConvertTo-DNA ($char) 55 | } 56 | } 57 | $DNA = @() 58 | $message = Read-Host "Enter your secret message" 59 | $message = $message.ToCharArray() 60 | ForEach($character in $message){ 61 | $charNum = [byte][char]$character 62 | If($charNum -lt 64){ 63 | $DNA+= "A" 64 | ConvertTo-Quad ($charNum) 65 | }Else{ 66 | ConvertTo-Quad ($charNum) 67 | } 68 | } 69 | "$DNA" -------------------------------------------------------------------------------- /HackerTypist.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | A fun goof. Provide any file, preferrably a script or source code file, to the -source parameter. 3 | When run, hacker_typist.ps1 will sequentially display random-length pieces of the 4 | source code file as you hit any keys on the keyboard, giving the appearance of a very fast 5 | typist writing the code. 6 | 7 | If you don't provide a $source file, this script itself will be used as the input text, skipping 8 | these first comment lines. 9 | 10 | Increase the value for $maximumIncrement to make "typing" appear faster 11 | 12 | Requires a PowerShell console because reading and writing keystrokes isn't supported by the ISE 13 | 14 | #> 15 | Param( 16 | $source, 17 | $maximumIncrement = 3 18 | ) 19 | If ($PSBoundParameters.ContainsKey('source')){ 20 | $source = Get-Content $source 21 | }Else{ 22 | $source = Get-Content $MyInvocation.InvocationName | Select -Skip 14 23 | } 24 | 25 | Clear-Host 26 | Write-Host "PS C:\>" -NoNewline 27 | $maximumIncrement ++ 28 | 29 | ForEach ($line in $source){ 30 | $index = 0 31 | $lineLength = $line.length 32 | Do{ 33 | If($host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")){ 34 | $increment = Get-Random -Minimum 1 -Maximum $maximumIncrement 35 | If(($index + $increment) -le $lineLength){ 36 | Write-Host $line.Substring($index,$increment) -NoNewline 37 | $index = $index + $increment 38 | }Else{ 39 | $remainder = $lineLength - $index 40 | Write-Host $line.Substring($index,$remainder) -NoNewline 41 | $index = $index + $increment 42 | } 43 | } 44 | }While($index -lt $line.length) 45 | Write-Host "`r" 46 | } 47 | -------------------------------------------------------------------------------- /Networking/LatencyTest.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | $loops = 60, 3 | $interval = 5 4 | ) 5 | cls 6 | $i = $null 7 | $d1Total = $null 8 | $d2Total = $null 9 | $d3Total = $null 10 | Write-Host -ForegroundColor Yellow -BackgroundColor DarkGray ("{0,-12}{1,9} {2,9} {3,9}" -f "Time","Verizon","Google","Yahoo") 11 | Do{ 12 | $d1 = Test-Connection 4.2.2.2 -Count 1 -ErrorAction SilentlyContinue 13 | $d2 = Test-Connection 8.8.8.8 -Count 1 -ErrorAction SilentlyContinue 14 | $d3 = Test-Connection www.yahoo.com -Count 1 -ErrorAction SilentlyContinue 15 | If($d1 -eq $null){$d1ResponseTime = 1000}Else{$d1ResponseTime = $d1.ResponseTime} 16 | If($d2 -eq $null){$d2ResponseTime = 1000}Else{$d2ResponseTime = $d2.ResponseTime} 17 | If($d3 -eq $null){$d3ResponseTime = 1000}Else{$d3ResponseTime = $d3.ResponseTime} 18 | $d1Total += $d1ResponseTime 19 | $d2Total += $d2ResponseTime 20 | $d3Total += $d3ResponseTime 21 | $i++ 22 | $d1Avg = ($d1Total/$i) 23 | $d2Avg = ($d2Total/$i) 24 | $d3Avg = ($d3Total/$i) 25 | Write-Host -ForegroundColor White ("{0,-8:hh:mm:ss}" -f (Get-Date)) -NoNewline 26 | If($d1ResponseTime -ge ($d1Avg * 2)){ 27 | Write-Host -ForegroundColor Red ("{0,10} ms" -f $d1ResponseTime) -NoNewline} Else{ 28 | Write-Host -ForegroundColor White ("{0,10} ms" -f $d1ResponseTime) -NoNewline} 29 | If($d2ResponseTime -ge ($d2Avg * 2)){ 30 | Write-Host -ForegroundColor Red ("{0,7} ms" -f $d2ResponseTime) -NoNewline} Else{ 31 | Write-Host -ForegroundColor White ("{0,7} ms" -f $d2ResponseTime) -NoNewline} 32 | If($d3ResponseTime -ge ($d3Avg * 2)){ 33 | Write-Host -ForegroundColor Red ("{0,7} ms" -f $d3ResponseTime)} Else{ 34 | Write-Host -ForegroundColor White ("{0,7} ms" -f $d3ResponseTime)} 35 | Sleep $interval 36 | }Until( 37 | $i -ge $loops 38 | ) 39 | -------------------------------------------------------------------------------- /GetOSReleaseId.ps1: -------------------------------------------------------------------------------- 1 | # Function to fetch the ReleaseId value from one or more Windows systems using WMI and the STDREG provider 2 | # (Windows clients don't have PowerShell remoting enabled by default, but WMI may be available) 3 | Function Get-OSReleaseID { 4 | [CmdletBinding()] 5 | Param ( 6 | [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] 7 | [string[]]$computerName = 'localhost' 8 | ) 9 | Process { 10 | $HKLM = 2147483650 11 | $key = "SOFTWARE\Microsoft\Windows NT\CurrentVersion" 12 | $releaseID = "ReleaseId" 13 | $productName = "ProductName" 14 | ForEach($computer in $computerName){ 15 | $ok = $true 16 | Try{ 17 | $wmi = [wmiclass]"\\$computer\root\default:stdRegProv" 18 | }Catch{ 19 | $ok = $false 20 | } 21 | If($ok){ 22 | $releaseIDValue = ($wmi.GetStringValue($HKLM,$key,$releaseID)).sValue 23 | $productNameValue = ($wmi.GetStringValue($HKLM,$key,$productName)).sValue 24 | $properties = @{ 25 | ComputerName = $computer 26 | ProductName = $productNameValue 27 | ReleaseID = $releaseIDValue 28 | } 29 | $return = New-Object -TypeName PSObject -Property $properties 30 | Write-Output $return 31 | }Else{ 32 | $properties = @{ 33 | ComputerName = $computer 34 | ProductName = 'UNKNOWN' 35 | ReleaseID = 'UNKNOWN' 36 | } 37 | $return = New-Object -TypeName PSObject -Property $properties 38 | Write-Output $return 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /InputBox.ps1: -------------------------------------------------------------------------------- 1 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 2 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 3 | 4 | $objForm = New-Object System.Windows.Forms.Form 5 | $objForm.Text = "Data Entry Form" 6 | $objForm.Size = New-Object System.Drawing.Size(300,200) 7 | $objForm.StartPosition = "CenterScreen" 8 | 9 | $objForm.KeyPreview = $True 10 | $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 11 | {$x=$objTextBox.Text;$objForm.Close()}}) 12 | $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 13 | {$objForm.Close()}}) 14 | 15 | $OKButton = New-Object System.Windows.Forms.Button 16 | $OKButton.Location = New-Object System.Drawing.Size(75,120) 17 | $OKButton.Size = New-Object System.Drawing.Size(75,23) 18 | $OKButton.Text = "OK" 19 | $OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()}) 20 | $objForm.Controls.Add($OKButton) 21 | 22 | $CancelButton = New-Object System.Windows.Forms.Button 23 | $CancelButton.Location = New-Object System.Drawing.Size(150,120) 24 | $CancelButton.Size = New-Object System.Drawing.Size(75,23) 25 | $CancelButton.Text = "Cancel" 26 | $CancelButton.Add_Click({$objForm.Close()}) 27 | $objForm.Controls.Add($CancelButton) 28 | 29 | $objLabel = New-Object System.Windows.Forms.Label 30 | $objLabel.Location = New-Object System.Drawing.Size(10,20) 31 | $objLabel.Size = New-Object System.Drawing.Size(280,20) 32 | $objLabel.Text = "Please enter the information in the space below:" 33 | $objForm.Controls.Add($objLabel) 34 | 35 | $objTextBox = New-Object System.Windows.Forms.TextBox 36 | $objTextBox.Location = New-Object System.Drawing.Size(10,40) 37 | $objTextBox.Size = New-Object System.Drawing.Size(260,20) 38 | $objForm.Controls.Add($objTextBox) 39 | 40 | $objForm.Topmost = $True 41 | 42 | $objForm.Add_Shown({$objForm.Activate()}) 43 | [void] $objForm.ShowDialog() 44 | 45 | $x 46 | -------------------------------------------------------------------------------- /Azure/GetVMFamilySizesByLocation.ps1: -------------------------------------------------------------------------------- 1 | Function Get-AzureVmSizesByLocation { 2 | <# 3 | .SYNOPSIS 4 | Given a VM family, displays the Azure regions where that VM may be hosted 5 | 6 | .EXAMPLE 7 | Get-AzureVmSizesByLocation -vmSeries Esv3 | Sort Size | Format-Table Location -GroupBy Size 8 | #> 9 | 10 | Param( 11 | [ValidateSet('Dv3','Dsv3','Ev3','Esv3')] 12 | [string]$vmSeries 13 | ) 14 | 15 | # Look for Az module and, if present, load the equivalent -AzureRm aliases: 16 | If(Get-Module -ListAvailable Az.*){ 17 | Enable-AzureRmAlias 18 | } 19 | 20 | # Check for Azure login: 21 | Try{ 22 | Get-AzureRmContext -ErrorAction Stop 23 | }Catch{ 24 | Add-AzureRmAccount 25 | } 26 | If(-not ($vmSeries -eq $null)){ 27 | Switch ($vmSeries){ 28 | 'Dv3' {$pattern = '\w+_D\d+_v3$'} 29 | 'Dsv3' {$pattern = '\w+_D\d+s_v3$'} 30 | 'Ev3' {$pattern = '\w+_E\d+_v3$'} 31 | 'Esv3' {$pattern = '\w+_E\d+s_v3$'} 32 | } 33 | } 34 | $locations = Get-AzureRmLocation | Select-Object -ExpandProperty location 35 | $locationCount = 0 36 | ForEach ($location in $locations){ 37 | $locationCount++ 38 | Write-Progress -Activity "Searching location.." -Status $location -PercentComplete ($locationCount/$locations.count * 100) 39 | $list = @() 40 | Try{ 41 | If(-not ($vmSeries -eq $null)){ 42 | $list += Get-AzureRmVmSize -Location $location -ErrorAction Stop | Where-Object {$_.Name -cmatch $pattern} | Select-Object -ExpandProperty Name 43 | }Else{ 44 | $list += Get-AzureRmVmSize -Location $location -ErrorAction Stop | Select -ExpandProperty Name 45 | } 46 | }Catch{ 47 | 48 | } 49 | ForEach ($size in $list){ 50 | $properties = @{ 51 | Size = $size 52 | Location = $location 53 | } 54 | $obj = New-Object -TypeName psobject -Property $properties 55 | Write-Output $obj 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Networking/FindShares.ps1: -------------------------------------------------------------------------------- 1 | # FindShares.ps1; 3/14/07 2 | 3 | # BEGIN CALLOUT A 4 | # BEGIN COMMENT 5 | # Define parameter to pass computer name when calling script file 6 | # Use the local computer if no name is specified 7 | # END COMMENT 8 | param ($computer = ".") 9 | # END CALLOUT A 10 | 11 | # BEGIN CALLOUT B 12 | # BEGIN COMMENT 13 | # Create a WMI object to access the win32_share class 14 | # Pass data down pipeline to filter to remove default shares 15 | # Then pass data down pipeline to short the results by name 16 | # END COMMENT 17 | $shares = get-wmiobject -class "Win32_share" ` 18 | -namespace "root\CIMV2" -computername $computer | 19 | where-object ` 20 | { 21 | ($_.caption -ne "default share") ` 22 | -and ($_.caption -notlike "remote*") ` 23 | -and ($_.caption -notlike "logon*") ` 24 | } | 25 | sort-object name 26 | # END CALLOUT B 27 | 28 | # BEGIN CALLOUT C 29 | # BEGIN COMMENT 30 | # Run if statement if user-defined shares exist 31 | # END COMMENT 32 | if ($shares -ne $null) 33 | { 34 | # BEGIN COMMENT 35 | # Add blank line before results 36 | # Then create foreach loop to iterate through shares 37 | # END COMMENT 38 | write-host 39 | foreach ($share in $shares) 40 | { 41 | # BEGIN COMMENT 42 | # For each share, provide name and path 43 | # END COMMENT 44 | write-host "Share name: " $share.name 45 | write-host "File path: " $share.path 46 | write-host 47 | } 48 | } 49 | # END CALLOUT C 50 | 51 | # BEGIN CALLOUT D 52 | # BEGIN COMMENT 53 | # Run else statement if user-defined shares do not exist 54 | # END COMMENT 55 | else 56 | { 57 | if ($computer -eq ".") 58 | { 59 | # BEGIN COMMENT 60 | # Return message that names the local computer 61 | # END COMMENT 62 | write-host 63 | write-host "The computer $env:computerName contains only the default shares." 64 | write-host 65 | } 66 | 67 | else 68 | { 69 | # BEGIN COMMENT 70 | # Return message that names the specified computer 71 | # END COMMENT 72 | write-host 73 | write-host "The computer $computer contains only the default shares." 74 | write-host 75 | } 76 | } 77 | # END CALLOUT D 78 | -------------------------------------------------------------------------------- /GetPwnedPassword.ps1: -------------------------------------------------------------------------------- 1 | Function Get-PwnedPassword { 2 | Param( 3 | [string]$passwordString, 4 | 5 | [switch]$showHashes 6 | ) 7 | 8 | # If a cleartext password wasn't provided, prompt for the password and obscure the typing: 9 | 10 | If($passwordString -eq ''){ 11 | $securePasswordString = Read-Host 'Enter the password string:' -AsSecureString 12 | 13 | # Extract the password string for processing: 14 | 15 | $passwordString = (New-Object PSCredential "user",$securePasswordString).GetNetworkCredential().Password 16 | } 17 | 18 | [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 19 | $passwordStringBuilder = New-Object System.Text.StringBuilder 20 | $byteArray = [System.Security.Cryptography.HashAlgorithm]::Create('SHA1').ComputeHash([System.Text.Encoding]::UTF8.GetBytes($passwordString)) 21 | ForEach ($byte in $byteArray) { 22 | [Void]$passwordStringBuilder.Append($byte.ToString("x2")) 23 | } 24 | $hash = $passwordStringBuilder.ToString() 25 | $prefix = $hash.Substring(0,5) 26 | $suffix = $hash.Substring(5,35) 27 | $results = Invoke-RestMethod -Uri https://api.pwnedpasswords.com/range/$prefix 28 | # Results are a single long string. Need to break out the individual hashes and number of matches: 29 | $results = ($results | Select-String "(\w{35}:\d{1,})" -AllMatches).Matches.Value 30 | # If($showHashes){ 31 | # ForEach($hash in $results){ 32 | # Write-Host $hash 33 | # } 34 | # } 35 | $unmatched = $true 36 | ForEach($entry in $results){ 37 | If($showHashes){ 38 | Write-Host $prefix$entry 39 | } 40 | $entry = $entry.split(':') 41 | If($entry[0] -eq $suffix){ 42 | Write-Host "THAT PASSWORD HAS BEEN SEEN IN $($entry[1]) BREACHES!!!" -ForegroundColor White -BackgroundColor DarkRed 43 | $unmatched = $false 44 | Break 45 | } 46 | } 47 | If($unmatched){ 48 | Write-Host 'Congratulations, that password does not appear to be exposed' -ForegroundColor Black -BackgroundColor White 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /GetFolderNTFS.ps1: -------------------------------------------------------------------------------- 1 | Function Get-FolderNTFSPermission{ 2 | Param( 3 | $computerName = ".", 4 | [Parameter(Mandatory=$True)]$rootPath, 5 | [switch]$recurse = $false 6 | ) 7 | $RecordErrorAction = $ErrorActionPreference 8 | $ErrorActionPreference = "SilentlyContinue" 9 | $folders = @() 10 | $rootPath = ($rootPath).Replace("\","\\") 11 | $directoryObject = Get-WMIObject Win32_Directory -filter "Name='$rootPath'" -ComputerName $computerName 12 | $folders += $directoryObject | Select-Object -ExpandProperty Name 13 | If($recurse){ 14 | $folders += $directoryObject.getrelated() | Where {$_.filetype -eq "File Folder"} | select -expandproperty name 15 | } 16 | foreach($path in $folders){ 17 | $Objs = @() 18 | #If($recurse){ 19 | # $FolderPath = ($path.FullName).Replace("\","\\") 20 | 21 | #}else{ 22 | $FolderPath = ($path).Replace("\","\\") 23 | 24 | # } 25 | $NTFSSecs = Get-WmiObject -Class Win32_LogicalFileSecuritySetting ` 26 | -Filter "Path='$FolderPath'" -ComputerName $ComputerName 27 | $SecDescriptor = $NTFSSecs.GetSecurityDescriptor() 28 | foreach($DACL in $SecDescriptor.Descriptor.DACL){ 29 | $DACLDomain = $DACL.Trustee.Domain 30 | $DACLName = $DACL.Trustee.Name 31 | if($DACLDomain -ne $null){ 32 | $UserName = "$DACLDomain\$DACLName" 33 | } 34 | else{ 35 | $UserName = "$DACLName" 36 | } 37 | $Properties = @{ 38 | 'ComputerName' = $ComputerName 39 | 'ConnectionStatus' = "Success" 40 | 'FolderName' = $path 41 | 'SecurityPrincipal' = $UserName 42 | 'FileSystemRights' = [Security.AccessControl.FileSystemRights]` 43 | $($DACL.AccessMask -as [Security.AccessControl.FileSystemRights]) 44 | 'AccessControlType' = [Security.AccessControl.AceType]$DACL.AceType 45 | 'AccessControlFlags' = [Security.AccessControl.AceFlags]$DACL.AceFlags 46 | } 47 | $NTFSACL = New-Object -TypeName PSObject -Property $Properties 48 | $Objs += $NTFSACL 49 | } 50 | $Objs |Select-Object ComputerName,ConnectionStatus,FolderName,SecurityPrincipal,FileSystemRights, ` 51 | AccessControlType,AccessControlFlags -Unique 52 | } 53 | $ErrorActionPreference = $RecordErrorAction 54 | } -------------------------------------------------------------------------------- /ActiveDirectory/DisableUser.ps1: -------------------------------------------------------------------------------- 1 | # DisableUser.ps1; 3/14/07 2 | 3 | # BEGIN CALLOUT A 4 | # BEGIN COMMENT 5 | # Define parameter to pass user account name when calling script file 6 | # END COMMENT 7 | param ($sam = $(throw "You must include the user account name.")) 8 | # END CALLOUT A 9 | 10 | # BEGIN CALLOUT B 11 | # BEGIN COMMENT 12 | # Create a searcher object to find data in Active Directory 13 | # END COMMENT 14 | $ds = new-object directoryServices.directorySearcher 15 | 16 | # BEGIN COMMENT 17 | #Define a filter on the searcher object to retrieve the specified user account 18 | # END COMMENT 19 | $ds.filter = "(&(objectCategory=person)(objectClass=user)(samAccountName=$sam))" 20 | 21 | # BEGIN COMMENT 22 | # Retrieve user account and assign to variable 23 | # END COMMENT 24 | $dn = $ds.findOne() 25 | # END CALLOUT B 26 | 27 | # BEGIN CALLOUT C 28 | # BEGIN COMMENT 29 | # Retrieve user account description and assign to variable 30 | # END COMMENT 31 | $desc = $dn.properties.description 32 | 33 | # BEGIN COMMENT 34 | # Retrieve timestamp and assign to variable 35 | # END COMMENT 36 | $date = get-date 37 | # END CALLOUT C 38 | 39 | # BEGIN CALLOUT D 40 | # BEGIN COMMENT 41 | # Run if statement if user account found 42 | # END COMMENT 43 | if ($dn.path.length -gt 0) 44 | { 45 | # BEGIN COMMENT 46 | # Create an ADSI object based on the user account path 47 | # END COMMENT 48 | $user = [ADSI]$dn.path 49 | 50 | # BEGIN COMMENT 51 | # Disable the user account 52 | # END COMMENT 53 | $user.psBase.invokeSet("accountDisabled", $true) 54 | 55 | # BEGIN COMMENT 56 | # Append the user account description 57 | # END COMMENT 58 | $user.Put("description", "$desc (disabled $date)") 59 | 60 | # BEGIN COMMENT 61 | # Commit changes to the user account 62 | # END COMMENT 63 | $user.setInfo() 64 | 65 | # BEGIN COMMENT 66 | # Return message saying that the user account has been disabled 67 | # END COMMENT 68 | write-host "User account" $sam "disabled." 69 | 70 | # BEGIN COMMENT 71 | # Return the user account's distinguished name 72 | # END COMMENT 73 | write-host "Distinguished name:" $dn.properties.distinguishedname 74 | } 75 | # END CALLOUT D 76 | 77 | # BEGIN CALLOUT E 78 | # BEGIN COMMENT 79 | # Run else statement if user account not found 80 | # END COMMENT 81 | else 82 | # BEGIN COMMENT 83 | # Return message saying that user account was not found 84 | # END COMMENT 85 | {write-host "User account" $sam "not found."} 86 | # END CALLOUT E 87 | -------------------------------------------------------------------------------- /DynamicParameterValidateSetExample.ps1: -------------------------------------------------------------------------------- 1 | # the dynamic function is borrowed from Martin Schvartzman at 2 | # http://blogs.technet.com/b/pstips/archive/2014/06/10/dynamic-validateset-in-a-dynamic-parameter.aspx 3 | Function Get-Uptime { 4 | [CmdletBinding()] 5 | Param( 6 | [switch]$friendlyDate 7 | ) 8 | DynamicParam { 9 | # Set the dynamic parameters' name 10 | $ParameterName = 'ComputerName' 11 | 12 | # Create the dictionary 13 | $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary 14 | 15 | # Create the collection of attributes 16 | $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] 17 | 18 | # Create and set the parameters' attributes 19 | $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute 20 | $ParameterAttribute.Mandatory = $true 21 | $ParameterAttribute.Position = 1 22 | # Add the attributes to the attributes collection 23 | $AttributeCollection.Add($ParameterAttribute) 24 | 25 | # Generate and set the ValidateSet 26 | $arrSet = Get-ADComputer -Filter * | Select-Object -ExpandProperty Name 27 | $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) 28 | 29 | # Add the ValidateSet to the attributes collection 30 | $AttributeCollection.Add($ValidateSetAttribute) 31 | 32 | # Create and return the dynamic parameter 33 | $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string[]], $AttributeCollection) 34 | $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) 35 | return $RuntimeParameterDictionary 36 | } 37 | Begin{ 38 | # Bind the parameter to a friendly variable 39 | $ComputerName = $PsBoundParameters[$ParameterName] 40 | } 41 | Process{ 42 | ForEach($computer in $computerName){ 43 | If($friendlyDate){ 44 | Get-WMIObject -Class Win32_OperatingSystem -ComputerName $computer | 45 | Select @{Label="Uptime";Expression={$_.ConvertToDateTime($_.LastBootupTime)}} 46 | }else{ 47 | Get-WMIObject -Class Win32_OperatingSystem -ComputerName $computer | Select LastBootupTime 48 | } 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /Networking/AddDHCPReservations.ps1: -------------------------------------------------------------------------------- 1 | # Example: .\AddDHCPReservations.ps1 -DHCPServer 'LON-DC1' -DHCPScopeId '172.16.0.0' 2 | Param( 3 | [string]$subnet = '172.16.0.', 4 | [array]$hosts = 9..11, 5 | [string]$fakeMACPrefixNoPing = 'AA-AA-AA', 6 | [string]$fakeMACPrefixNoWMI = 'BB-BB-BB', 7 | [string]$DHCPServer, 8 | [string]$DHCPScopeId 9 | ) 10 | 11 | Function Search-Subnet { 12 | Param( 13 | [string]$subnet, 14 | [array]$hosts 15 | ) 16 | ForEach($hostIP in $hosts){ 17 | # NOTE: because we're connecting to WMI using an IP, it's a good idea 18 | # to make sure you've registered DNS reverse lookup records for the machine. Otherwise, 19 | # Kerberos auth will take MUCH longer for each IP 20 | $computer = "$subnet$hostIP" 21 | $pingResult = Test-NetConnection -ComputerName $computer -WarningAction SilentlyContinue 22 | If($pingResult.PingSucceeded){ 23 | $properties = @{ 24 | PingSucceeded = $pingResult.PingSucceeded 25 | IPAddress = $pingResult.RemoteAddress 26 | } 27 | 28 | Try{ 29 | # Get-WMIObject query assumes a single physical NIC 30 | $nic = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $computer -Filter "IPEnabled=$true" -ErrorAction Stop 31 | $properties.Add('hostName',$nic.PSComputerName) 32 | $properties.Add('ClientId',$($nic.MACAddress -replace ':','-')) 33 | }Catch{ 34 | $properties.Add('hostname','WMI_FAILED') 35 | $properties.Add('ClientId',(New-RandomMACSuffix -MACPrefix $fakeMACPrefixNoWMI)) 36 | } 37 | }Else{ 38 | $properties = @{ 39 | PingSucceeded = $pingResult.PingSucceeded 40 | IPAddress = $pingResult.RemoteAddress 41 | hostName = "UNAVAILABLE" 42 | ClientId = (New-RandomMACSuffix -MACPrefix $fakeMACPrefixNoPing) 43 | } 44 | } 45 | $obj = New-Object -TypeName PSObject -Property $properties 46 | Write-Output $obj 47 | } 48 | } 49 | 50 | Function New-RandomMACSuffix { 51 | Param( 52 | [string]$MACPrefix 53 | ) 54 | $MACSuffix = '{0:X6}' -f (Get-Random -Maximum 16777215) 55 | $MACSuffix = $MACSuffix -replace '(\w{2})(\w{2})(\w{2})', '$1-$2-$3' 56 | Write-Output "$MACPrefix-$MACSuffix" 57 | } 58 | 59 | Search-Subnet -subnet $subnet -hosts $hosts | Add-DhcpServerv4Reservation -ComputerName $DHCPServer -ScopeId $DHCPScopeId -ErrorAction SilentlyContinue 60 | -------------------------------------------------------------------------------- /CompareDictionary.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [switch]$includeEqual 3 | ) 4 | $table1 = @{ 5 | ServerA = '1.1.1.1' 6 | ServerB = '1.1.1.2' 7 | ServerD = '1.1.1.4' 8 | } 9 | 10 | $table2 = @{ 11 | ServerA = '1.1.1.1' 12 | ServerB = '1.1.1.23' 13 | ServerC = '1.1.1.3' 14 | } 15 | 16 | $results = @() 17 | # Initialize an Arraylist to hold the $table2 entries: 18 | $unmatchedTable2Keys = [System.Collections.ArrayList]::new() 19 | ForEach ($table2Entry in $table2.GetEnumerator().Name){ 20 | $unmatchedTable2Keys.Add($table2Entry) | Out-Null 21 | } 22 | 23 | ForEach($entry in $table1.GetEnumerator()){ 24 | $propList = [ordered]@{ 25 | Table_1_Key = $entry.Name 26 | Table_1_Value = $entry.Value 27 | } 28 | # Does the key in the first table exist in the second table? 29 | 30 | If($entry.Name -in $table2.Keys){ 31 | 32 | # If it does, remove it from $unmatchedTable2Items: 33 | $unmatchedTable2Keys.Remove($entry.Name) 34 | 35 | # Is the value the same or different between the two tables? 36 | 37 | If($entry.Value -eq $table2.($entry.Name)){ 38 | If($includeEqual){ 39 | $propList.Add('Equality','==') 40 | $propList.Add('Table_2_Key',"$($entry.Name)") 41 | $propList.Add('Table_2_Value',"$($table2.($entry.Key))") 42 | $results += New-Object -TypeName PSObject -Property $propList 43 | } 44 | }Else{ 45 | # mismatch - record the difference 46 | $propList.Add('Equality','<>') 47 | $propList.Add('Table_2_Key',"$($entry.Name)") 48 | $propList.Add('Table_2_Value',"$($table2.($entry.Key))") 49 | $results += New-Object -TypeName PSObject -Property $propList 50 | #"$($entry.Name) $($entry.Value) <> $($entry.Name) $($table2.($entry.Key))" 51 | } 52 | }Else{ 53 | # mismatch - There's a new entry in the first table 54 | $propList.Add('Equality','<=') 55 | $propList.Add('Table_2_Key','-') 56 | $propList.Add('Table_2_Value','-') 57 | $results += New-Object -TypeName PSObject -Property $propList 58 | #"$($entry.Name) = $($entry.Value) <= NEW" 59 | } 60 | } 61 | 62 | # Check if there are any entries remaining in the second table: 63 | If($unmatchedTable2Keys.Count -gt 0){ 64 | ForEach($key in $unmatchedTable2Keys){ 65 | $propList = [ordered]@{ 66 | Table_1_Key = '-' 67 | Table_1_Value = '-' 68 | Equality = '=>' 69 | Table_2_Key = $key 70 | Table_2_Value = $table2.$key 71 | } 72 | $results += New-Object -TypeName PSObject -Property $propList 73 | #"NEW => $key = $($table2.$key)" 74 | } 75 | } 76 | 77 | $results -------------------------------------------------------------------------------- /ActiveDirectory/CompareUsers.ps1: -------------------------------------------------------------------------------- 1 | #Updated 2-15-2018 2 | #Note: When the first user in the comparison contains a very long attribute value (for example, the MemberOf property), the second 3 | #user may be pushed beyond the console's right boundary. If you extend the console enough before running the command, the 4 | #second user column will be displayed. Alternatively, you can export the pipeline to CSV, XML, or another format (but not 5 | #Out-File 6 | 7 | Function Compare-User { 8 | Param( 9 | [Parameter(Mandatory=$true)][string]$firstuser, 10 | [Parameter(Mandatory=$true)][string]$seconduser, 11 | [string]$firstDC, 12 | [int]$firstDCPort = 389, 13 | [string]$secondDC, 14 | [int]$secondDCPort = 389, 15 | [switch]$showMetaData = $false 16 | ) 17 | $metaDataProps = @( 18 | 'Created', 19 | 'createTimeStamp', 20 | 'Modified', 21 | 'modifyTimeStamp', 22 | 'ObjectGUID', 23 | 'objectSid', 24 | 'pwdLastSet', 25 | 'sDRightsEffective', 26 | 'uSNChanged', 27 | 'uSNCreated', 28 | 'whenChanged', 29 | 'whenCreated' 30 | ) 31 | If(! $firstDC){ 32 | $firstDC = Get-ADDomainController | Select-Object -ExpandProperty Hostname 33 | } 34 | If(! $secondDC){ 35 | $secondDC = Get-ADDomainController | Select-Object -ExpandProperty Hostname 36 | } 37 | $snapshot = Get-ADUser $firstUser -Properties * -Server "$firstDC`:$firstDCPort" 38 | $now = Get-ADUser $secondUser -Properties * -Server "$secondDC`:$secondDCPort" 39 | $masterPropList = @() 40 | $masterPropList = $snapshot | Get-Member -MemberType Property | Select -ExpandProperty Name # Get the prop list from the first user 41 | $masterPropList += $now | Get-Member -MemberType Property | Select -ExpandProperty Name # ...and the second user 42 | $masterPropList = $masterPropList | Select-Object -Unique # Combine the properties, selecting only those that are unique 43 | If(-not $showMetaData){ 44 | $shortPropList = @() 45 | ForEach($name in $masterPropList){ 46 | If($metaDataProps -notcontains $name){ 47 | $shortPropList += $name 48 | } 49 | } 50 | $masterPropList = $shortPropList 51 | } 52 | ForEach($property in $masterPropList){ 53 | If($compare = Compare-Object $snapshot $now -Property $property){ 54 | $hash = @{ 55 | Property = $property; 56 | "$FirstUser" = $compare[1].$property; 57 | "$SecondUser" = $compare[0].$property 58 | } 59 | $PSObject = New-Object -TypeName PSObject -Property $hash 60 | Write-Output $PSObject | Select Property, "$FirstUser", "$SecondUser" 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /Azure/GetVMSizesByLocation.ps1: -------------------------------------------------------------------------------- 1 | 2 | 3 | Function Get-AzureVmSizeByLocation { 4 | <# 5 | .SYNOPSIS 6 | Given a VM size, displays the Azure regions where that VM may be hosted in the current subscription 7 | 8 | .EXAMPLE 9 | Get-AzureVmSizeByLocation -vmSize Standard_D1_v2 10 | 11 | .EXAMPLE 12 | Get-AzureVmSizeByLocation -vmSize Standard_DS1_v2 | Sort Size | Format-Table LocationAvailable -GroupBy Size 13 | 14 | .EXAMPLE 15 | Get-AzureVmSizeByLocation -vmSize Standard_D2_v2 -location westus2 16 | 17 | .EXAMPLE 18 | Get-AzureVmSizeByLocation | Sort locationAvailable | Format-Table Size -GroupBy locationAvailable 19 | #> 20 | 21 | Param( 22 | [ValidateSet( # common sizes used in MOC AZ-103T00 23 | 'Standard_DS1_v2', 24 | 'Standard_DS2_v2', 25 | 'Standard_D1_v2', 26 | 'Standard_D2_v2', 27 | 'Standard_D2s_v3' # used in Module 9 28 | )] 29 | [string]$vmSize, 30 | 31 | [string]$location # optional 32 | ) 33 | 34 | # Check for Azure login: 35 | Write-Progress -Activity 'Checking for Azure logon...' 36 | Try{ 37 | Get-AzContext -ErrorAction Stop | Out-Null 38 | }Catch{ 39 | Add-AzAccount 40 | } 41 | Write-Progress -Activity 'Fetching Azure locations available to your subscription...' 42 | $locations = Get-AzLocation | Select-Object -ExpandProperty location 43 | If($PSBoundParameters.ContainsKey('location')){ 44 | If($locations -contains $location){ 45 | $locations = $location 46 | }Else{ 47 | throw "INVALID LOCATION" 48 | } 49 | } 50 | $locationCount = 0 51 | Write-Progress -Activity 'Fetching list of all possible VM SKUs...' 52 | $allVmSKUs = Get-AzComputeResourceSku | Where-Object {$_.ResourceType -like 'virtualMachines' -and $_.Restrictions.ReasonCode -ne 'NotAvailableForSubscription'} 53 | ForEach ($location in $locations){ 54 | $locationCount++ 55 | Write-Progress -Activity "Searching location.." -Status $location -PercentComplete ($locationCount/$locations.count * 100) 56 | $list = @() 57 | Try{ 58 | If(-not ($vmSize -eq $null)){ 59 | $list += $allVmSKUs | 60 | Where-Object {$_.Locations -contains $location -and $_.Name -match $vmSize} | Select-Object -ExpandProperty Name 61 | }Else{ 62 | $list += $allVmSKUs | 63 | Where-Object {$_.Locations -contains $location} | Select-Object -ExpandProperty Name 64 | } 65 | }Catch{ 66 | 67 | } 68 | $objList = @() 69 | ForEach ($size in $list){ 70 | $properties = @{ 71 | Size = $size 72 | LocationAvailable = $location 73 | } 74 | $objList += New-Object -TypeName psobject -Property $properties 75 | } 76 | Write-Output $objList 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /DeadMan.ps1: -------------------------------------------------------------------------------- 1 | # The WriteTo-Pos function is taken from Tibor Soos at 2 | # http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/26/hey-scripting-guy-march-26-2010.aspx?Redirected=true 3 | # It doesn't work in the PowerShell ISE, only in the console, so if you want to see the deadman seconds counting 4 | # down, you need to run Dead-Man from an ordinary PowerShell console. 5 | 6 | function WriteTo-Pos ([string] $str, [int] $x = 0, [int] $y = [console]::CursorTop, # adjusted this to do countdown in-line with PS prompt 7 | [string] $bgc = [console]::BackgroundColor, 8 | [string] $fgc = [Console]::ForegroundColor) 9 | { 10 | if($x -ge 0 -and $y -ge 0 -and $x -le [Console]::WindowWidth -and 11 | $y -le [Console]::WindowHeight) 12 | { 13 | $saveY = [console]::CursorTop 14 | $offY = [console]::WindowTop 15 | [console]::setcursorposition($x,$offY+$y) 16 | Write-Host -Object $str -BackgroundColor $bgc ` 17 | -ForegroundColor $fgc -NoNewline 18 | [console]::setcursorposition(0,$saveY) 19 | } 20 | } 21 | 22 | #The Dead-Man function is mine, but it uses a couple of the techniques from the same source, 23 | # http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/26/hey-scripting-guy-march-26-2010.aspx?Redirected=true 24 | 25 | Function Dead-Man{ 26 | # An example of a PowerShell "dead man" switch. Someone must press a key within numSec number of seconds, or the script 27 | # will quit/continue/whatever. If a key is clicked, the counter starts over at numSec again. 28 | 29 | Param( 30 | $numSec = 5 31 | ) 32 | $originalLength = $numSec.ToString().Length 33 | Do{ 34 | $key = $null 35 | For($i = $numSec;$i -ge 0;$i--){ #For loop is so we can display an update each second 36 | WriteTo-Pos "$i$(' ' * $($originalLength - $i.ToString().Length))" # This code is because the countdown will display digits from earlier columns without it. 37 | # So we get the original number of digits in numSec, then multiply the difference between the original number of digits and the current number by a space character. 38 | # This way, the WriteTo-Pos function will add extra space after shorter digits to hide the previous columns in the countdown. 39 | If([console]::KeyAvailable){break} #If is necessary to restart timer when a key is pressed 40 | Sleep 1 41 | } 42 | while([console]::KeyAvailable){ # Can't use $host variable here 43 | $key = [console]::Readkey("NoEcho").Key # ...or here 44 | } 45 | If($key -eq $null){ 46 | Write-Host "DEAD MAN!" 47 | [System.Media.SystemSounds]::Hand.Play() 48 | Sleep -Milliseconds 500 49 | [System.Media.SystemSounds]::Hand.Play() 50 | Sleep -Milliseconds 500 51 | [System.Media.SystemSounds]::Hand.Play() 52 | break 53 | } 54 | #Write-Host "Current key is $key" 55 | }While($true) 56 | } -------------------------------------------------------------------------------- /DSC/DscCertDemo.ps1: -------------------------------------------------------------------------------- 1 | # For a DSC Demo using 55202 Lab on Demand VMs 2 | # Run from StudentServer2. If you run the script from any other system, you'll need to import the certificate 3 | # into the destination system's local machine certificate store before the configuration can be pushed or pulled 4 | 5 | Param( 6 | [string]$computerName = 'StudentServer2', 7 | [string]$dirPath = 'C:\CERTDEMO' 8 | ) 9 | 10 | If(-not (Test-Path $dirPath)){ 11 | New-Item $dirPath -ItemType Directory 12 | } 13 | # Grab Adam Bertram's New-SelfSignedCertificateEx if necessary (New-SelfSignedCertificate before Windows 10/Server 2016 doesn't support 14 | # the necessary parameters for a DSC certicate): 15 | 16 | If(-not (Test-Path "$dirpath\New-SelfSignedCertificateEx.ps1")){ 17 | $pathToScript = "https://raw.githubusercontent.com/adbertram/Random-PowerShell-Work/f88241b7942e343eeef08ab583212e682df89eb3/Security/New-SelfSignedCertificateEx.ps1" 18 | Invoke-WebRequest -Uri $pathToScript -OutFile C:\CERTDEMO\New-SelfSignedCertificateEx.ps1 19 | } 20 | 21 | # Define the parameters required for a DSC cert: 22 | $certParams = @{ 23 | 'Subject' = "CN=$computerName" 24 | 'SAN' = $computerName 25 | 'EnhancedKeyUsage' = 'Document Encryption' 26 | 'KeyUsage' = 'KeyEncipherment', 'DataEncipherment' 27 | 'FriendlyName' = 'DSC Encryption Certifificate' 28 | 'StoreLocation' = 'LocalMachine' 29 | 'StoreName' = 'My' 30 | 'ProviderName' = 'Microsoft Enhanced Cryptographic Provider v1.0' 31 | 'PassThru' = $true 32 | 'KeyLength' = 2048 33 | 'AlgorithmName' = 'RSA' 34 | 'SignatureAlgorithm' = 'SHA256' 35 | } 36 | # Use New-SelfSignedCertificateEx to generate a self-signed cert for the local host 37 | . "$dirPath\New-SelfSignedCertificateEx.ps1" 38 | $cert = New-SelfSignedCertificateEx @certParams 39 | 40 | # Export the certificate for the MOF compilation system 41 | $cert | Export-Certificate -FilePath "$dirPath\$computerName.cer" 42 | 43 | # Configuration Data section 44 | $configData = @{ 45 | AllNodes = @( 46 | @{ 47 | NodeName = "*" 48 | } 49 | @{ 50 | NodeName = $computerName 51 | CertificateFile = "$dirPath\$computerName.cer" # local path where MOF is being compiled 52 | CertificateID = $cert.Thumbprint 53 | } 54 | ) 55 | } 56 | 57 | # Update the host Local Configuration Manager meta-config to include the CertificateID 58 | [DSCLocalConfigurationManager()] 59 | configuration LCMConfig 60 | { 61 | Node $AllNodes.NodeName 62 | { 63 | Settings 64 | { 65 | CertificateID = $Node.CertificateID 66 | } 67 | } 68 | } 69 | LCMConfig -OutputPath $dirPath -ConfigurationData $configData 70 | Set-DscLocalConfigurationManager -Path $dirPath -ComputerName $computerName 71 | 72 | # System configuration example. The credentials will be encrypted in the resulting MOF 73 | Configuration LocalAccounts { 74 | Import-DscResource -ModuleName 'PSDesiredStateConfiguration' 75 | Node $AllNodes.NodeName { 76 | 77 | User UserResourceExample { 78 | Ensure = 'Present' 79 | UserName = 'Bob' 80 | Password = (Get-Credential -UserName "Bob" -Message "Enter the password for the new user") 81 | } 82 | 83 | Group GroupResourceExample { 84 | GroupName = "ExampleGroup" 85 | Members = "Bob","BlueBuffalo\Administrator" 86 | Credential = (Get-Credential -Message 'Enter domain user credentials') 87 | DependsOn = "[User]UserResourceExample" 88 | } 89 | } 90 | } 91 | 92 | LocalAccounts -OutputPath $dirPath -ConfigurationData $configData 93 | -------------------------------------------------------------------------------- /Networking/Wifi.ps1: -------------------------------------------------------------------------------- 1 | $networks_raw = netsh wlan show networks mode=bssid | Select -Skip 4 2 | #$networks_raw = Get-Content C:\Users\Shawn.ELYSIUM\Desktop\wifi_short.txt | Select -Skip 4 #"netsh wlan show" uses header info for the first 4 lines 3 | $networkLines = @() 4 | $results = @() 5 | ForEach($line in $networks_raw){ 6 | If($line -ne ""){ 7 | $networkLines += $line 8 | }Else{ 9 | $network_segment = $networkLines 10 | $property_table = @{} 11 | $go_to_next_network = $false 12 | ForEach ($network_line in $network_segment){ # After BSSID processing, we shouldn't start back here.... 13 | If($go_to_next_network){Continue} # ....so we just continue and until we've exited the ForEach loop 14 | If($network_line -cnotlike "*BSSID*:*"){ # we'll implement a specialized routine to handle BSSIDs 15 | $split_line = $network_line -split ' :' # using a space and colon (" :") for the pattern so that MAC addresses aren't split into pieces 16 | If($split_line[0] -like "*SSID *"){ 17 | If($split_line[1] -match '^\s+$'){ # find SSIDS with empty strings so we can label them as 18 | $SSID_name = "" 19 | $property_table.Add("SSID",$SSID_name) 20 | }Else{ 21 | $SSID_name = $split_line[1].Trim() 22 | $property_table.Add("SSID",$SSID_name) 23 | } 24 | }Else{ 25 | $property_table.Add($split_line[0].Trim(),$split_line[1].Trim()) 26 | } 27 | }Else{ 28 | $BSSID_collection = @() 29 | $BSSIDs = $network_segment | Select-String -SimpleMatch "BSSID" -Context 0,5 30 | $BSSID_number = 0 31 | ForEach($BSSID in $BSSIDs){ 32 | $BSSID_number++ 33 | $BSSID = $BSSID -split "`n" # the context object produced by Select-String is a single string. We need to split it up. 34 | $BSSID_props = @{} 35 | $BSSID_props.Add("SSID",$SSID_name) 36 | ForEach($BSSID_line in $BSSID){ 37 | $split_line = $BSSID_line -split ' :' 38 | If($split_line[0] -match '>\s+BSSID'){$split_line[0] = "BSSID"} 39 | $BSSID_props.Add($split_line[0].Trim(),$split_line[1].Trim()) 40 | } 41 | $BSSID_obj = New-Object -TypeName PSObject -Property $BSSID_props 42 | $BSSID_collection += $BSSID_obj 43 | } 44 | $property_table.Add("BSSIDs",$BSSID_Collection) 45 | $netObj = New-Object -TypeName PSObject -Property $property_table 46 | $results += Write-Output $netObj 47 | Write-Output $netObj #| Select SSID,'Network Type',Encryption,Authentication,BSSID* # It's preferrable not to do selection or formatting here. Just a shortcut for now :) 48 | $network_segment = @() 49 | $property_table = @{} 50 | $go_to_next_network = $true # so we can exit the ForEach and continue to the next network 51 | } 52 | } 53 | $networkLines = @() 54 | } 55 | } 56 | 57 | # Examples: 58 | # 59 | # $results = .\wifi.ps1 60 | # $results.bssids | Format-Table -groupby SSID 61 | # 62 | #$results 63 | #TODO 64 | # When formatting the output, only the BSSID 1 displays.... 65 | # Convert to Function 66 | # Document with help 67 | # Is there a way to get netsh to update the list of wireless networks on its own? In Windows 10, at least, I have to 68 | # click the Networks icon, which refreshes the list of nets, before netsh sees the networks 69 | # 70 | # 71 | # 72 | # 73 | 74 | -------------------------------------------------------------------------------- /SetConsoleFont.ps1: -------------------------------------------------------------------------------- 1 | #requires -Version 2.0 2 | 3 | $STD_OUTPUT_HANDLE = -11 4 | 5 | $source = @" 6 | public delegate bool SetConsoleFont( 7 | IntPtr hWnd, 8 | uint DWORD 9 | ); 10 | 11 | public delegate uint GetNumberOfConsoleFonts(); 12 | 13 | public delegate bool GetConsoleFontInfo( 14 | IntPtr hWnd, 15 | bool BOOL, 16 | uint DWORD, 17 | [Out] CONSOLE_FONT_INFO[] ConsoleFontInfo 18 | ); 19 | 20 | 21 | [StructLayout(LayoutKind.Sequential)] 22 | public struct CONSOLE_FONT_INFO 23 | { 24 | public uint nFont; 25 | public COORD dwFontSize; 26 | } 27 | 28 | [StructLayout(LayoutKind.Sequential)] 29 | public struct COORD 30 | { 31 | public short X; 32 | public short Y; 33 | } 34 | 35 | [DllImport("kernel32.dll")] 36 | public static extern IntPtr GetModuleHandleA( 37 | string module 38 | ); 39 | 40 | [DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)] 41 | public static extern IntPtr GetProcAddress( 42 | IntPtr hModule, 43 | string procName 44 | ); 45 | 46 | [DllImport("kernel32.dll", SetLastError = true)] 47 | public static extern IntPtr GetStdHandle( 48 | int nStdHandle 49 | ); 50 | 51 | [DllImport("kernel32.dll", SetLastError = true)] 52 | public static extern bool GetCurrentConsoleFont( 53 | IntPtr hConsoleOutput, 54 | bool bMaximumWindow, 55 | out CONSOLE_FONT_INFO lpConsoleCurrentFont 56 | ); 57 | "@ 58 | 59 | 60 | Add-Type -MemberDefinition $source -Name Console -Namespace Win32API 61 | 62 | 63 | $_hmod = [Win32API.Console]::GetModuleHandleA("kernel32") 64 | 65 | "SetConsoleFont", "GetNumberOfConsoleFonts", "GetConsoleFontInfo" | 66 | % { 67 | $param = @() 68 | $proc = [Win32API.Console]::GetProcAddress($_hmod, $_) 69 | $delegate = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($proc, "Win32API.Console+$_") 70 | 71 | $delegate.Invoke.OverloadDefinitions[0] -match "^[^(]+\((.*)\)" > $null 72 | $argtypes = $Matches[1] -split ", " | 73 | ? { $_ } | 74 | % { 75 | '[{0}] ${1}' -f ($_ -split " "); 76 | $param += "$" + ($_ -split " ")[-1] 77 | } 78 | $argtypes = $argtypes -join ", " 79 | $param = $param -join ", " 80 | iex @" 81 | function $_($argtypes){ 82 | `$$_ = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($proc, 'Win32API.Console+$_') 83 | `$$_.Invoke( $param ) 84 | } 85 | "@ 86 | 87 | } 88 | 89 | $_hConsoleScreen = [Win32API.Console]::GetStdHandle($STD_OUTPUT_HANDLE) 90 | 91 | function Get-ConsoleFontInfo() 92 | { 93 | $_FontsNum = GetNumberOfConsoleFonts 94 | $_ConsoleFonts = New-Object Win32API.Console+CONSOLE_FONT_INFO[] $_FontsNum 95 | 96 | GetConsoleFontInfo $_hConsoleScreen $false $_FontsNum $_ConsoleFonts > $null 97 | 98 | $_ConsoleFonts | select @{l="nFont";e={$_ConsoleFonts.Count-$_.nFont-1}}, @{l="dwFontSizeX";e={$_.dwFontSize.X}}, @{l="dwFontSizeY";e={$_.dwFontSize.Y}} | sort nFont 99 | 100 | } 101 | 102 | 103 | $_DefaultFont = New-Object Win32API.Console+CONSOLE_FONT_INFO 104 | [Win32API.Console]::GetCurrentConsoleFont($_hConsoleScreen, $true, [ref]$_DefaultFont) 105 | 106 | function Set-ConsoleFont ([Uint32]$DWORD=$_DefaultFont.nFont, [IntPtr]$hWnd=$_hConsoleScreen) 107 | { 108 | $flag = SetConsoleFont $hWnd $DWORD 109 | if ( !$flag ) { throw "Illegal font index number. Check correct number using 'Get-ConsoleFontInfo'." } 110 | } 111 | 112 | 113 | 114 | #Export-ModuleMember -Variable _DefaultFont, _hConsoleScreen ` 115 | # -Function Set-ConsoleFont, Get-ConsoleFontInfo -------------------------------------------------------------------------------- /SendTextMessage.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | A function to make use of a cellular provider's SMS gateway to send a text through email 4 | .DESCRIPTION 5 | Many cellular carriers provide an SMS gateway service that forwards SMTP email as a text message. The "mail to" attribute is the phone number of the recipient, 6 | and the destination domain is the SMS gateway of the recipient's cellular provider. 7 | .PARAMETER Provider 8 | The name of the recipient's cellular provider. 9 | .PARAMETER smtpServer 10 | The FQDN of an SMTP server you have access to route email through. Some common web-based SMTP services are: 11 | GMail................ smtp.gmail.com 12 | Outlook.............. smtp-mail.outlook.com 13 | Yahoo................ smtp.mail.yahoo.com 14 | .PARAMETER smtpPort 15 | The port number of the SMTP server. Traditional SMTP is port 25, but most servers now require a secure connection. SMTP over SSL is usually defined on port 465, 16 | and SMTP over TLS is usually defined on port 587 17 | .PARAMETER smtpUserName 18 | The user name with permission to use the SMTP server. You may need to reduce the security of the mail account to authenticate to the SMTP server. For example, 19 | you can adjust Yahoo account settings under Account Security --> Allow apps that use less secure sign in. Alternatively, you may be able to generate an application password for PowerShell to use 20 | the SMTP account. 21 | .PARAMETER smtpPassword 22 | Password for SMTP user 23 | .PARAMETER cellNumberToText 24 | The cell number you want to text. Must be on the provider's network defined by the "provider" parameter 25 | .PARAMETER subject 26 | "Subject" of the text. The subject might appear in parenthesis to the left of the text message, or it might not appear in the resulting text 27 | Send-MailMessage doesn't allow an empty string or null for the subject line, but a single whitespace (the default for Send-TextMessage) will 28 | often result in the subject line being removed from the text 29 | .PARAMETER textMessage 30 | The text message 31 | .EXAMPLE 32 | Send-TextMessage -provider Verizon -smtpServer smtp.mail.yahoo.com -smtpPort 587 -smtpUserName some_user@yahoo.com -smtpPassword Pa55w.rd ` 33 | -cellNumberToText 3035551234 -subject 'Hello!' -textMessage 'Here's my message' 34 | #> 35 | 36 | Function Send-TextMessage { 37 | Param( 38 | [Parameter(Mandatory=$true)] 39 | [ValidateSet( 40 | 'Verizon', 41 | 'ATT', 42 | 'TMobile', 43 | 'Sprint', 44 | 'VirginMobile', 45 | 'Tracfone', 46 | 'MetroPCS', 47 | 'BoostMobile', 48 | 'Cricket' 49 | )] 50 | [string]$provider, 51 | 52 | [Parameter(Mandatory=$true)] 53 | [string]$smtpServer, 54 | 55 | [Parameter(Mandatory=$true)] 56 | [int]$smtpPort, 57 | 58 | [string]$smtpUserName, 59 | 60 | $smtpPassword, # Can't cast as [string] because converting to securestring will fail 61 | 62 | [Parameter(Mandatory=$true)] 63 | [int64]$cellNumberToText, 64 | 65 | [string]$subject = ' ', 66 | 67 | [string]$textMessage 68 | ) 69 | Switch ($provider){ 70 | Verizon {$domain='vtext.com'; break} 71 | ATT {$domain='txt.att.net'; break} 72 | TMobile{$domain='tmomail.net'; break} 73 | Sprint{$domain='messaging.sprintpcs.com'; break} 74 | VirginMobile{$domain='vmobl.com'; break} 75 | Tracfone{$domain='mmst5.tracfone.com'; break} 76 | MetroPCS{$domain='mymetropcs.com'; break} 77 | BoostMobile{$domain='sms.myboostmobile.com'; break} 78 | Cricket{$domain='sms.cricketwireless.net'; break} 79 | } 80 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 81 | $smtpPassword = ConvertTo-SecureString $smtpPassword -AsPlainText -Force 82 | $credential = New-Object System.Management.Automation.PSCredential($smtpUserName,$smtpPassword) 83 | $mailValues = @{ 84 | From = $smtpUserName 85 | To = "$cellNumberToText@$domain" 86 | Subject = $subject 87 | Body = $textMessage 88 | SmtpServer = $smtpServer 89 | Port = $smtpPort 90 | Credential = $credential 91 | UseSsl = $true 92 | } 93 | Send-MailMessage @mailValues 94 | } -------------------------------------------------------------------------------- /Azure/AzurePowerShell.ps1: -------------------------------------------------------------------------------- 1 | Function IsAdmin 2 | { 3 | $IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()` 4 | ).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") 5 | Return $IsAdmin 6 | } 7 | 8 | Function InstallWinRMCertificateForVM() 9 | { 10 | # This code sourced from https://gallery.technet.microsoft.com/scriptcenter/Configures-Secure-Remote-b137f2fe 11 | param( 12 | [string]$CloudServiceName, 13 | [string]$Name 14 | ) 15 | if((IsAdmin) -eq $false) 16 | { 17 | Write-Error "Must run PowerShell elevated to install WinRM certificates." 18 | return 19 | } 20 | 21 | Write-Host "Installing WinRM Certificate for remote access: $CloudServiceName $Name" 22 | $WinRMCert = (Get-AzureVM -ServiceName $CloudServiceName -Name $Name | Select-Object -ExpandProperty vm).DefaultWinRMCertificateThumbprint 23 | $AzureX509cert = Get-AzureCertificate -ServiceName $CloudServiceName -Thumbprint $WinRMCert -ThumbprintAlgorithm sha1 24 | 25 | $certTempFile = [IO.Path]::GetTempFileName() 26 | $AzureX509cert.Data | Out-File $certTempFile 27 | 28 | # Target The Cert That Needs To Be Imported 29 | $CertToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certTempFile 30 | 31 | $store = New-Object System.Security.Cryptography.X509Certificates.X509Store "Root", "LocalMachine" 32 | $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) 33 | $store.Add($CertToImport) 34 | $store.Close() 35 | 36 | Remove-Item $certTempFile 37 | } 38 | 39 | Function Setup-AzureRemotePS{ 40 | <# 41 | .SYNOPSIS 42 | Prepares the local host to use PowerShell remoting for Azure VMs 43 | .DESCRIPTION 44 | Setup-AzureRemotePS configures the local machine to use PowerShell remoting for Azure VMs. It 45 | either modifies the local TrustedHosts store and attempts to authenticate without certificate 46 | validation (in unsecure mode), or it will use InstallWinRMCertificateForVM to install the 47 | VM certificate in the local root store (when the -Secure switch is used) 48 | .PARAMETER cloudName 49 | The name of the Azure cloud service containing the VM. The Get-AzureService command can be 50 | used to view cloud service names in the current Azure subscription. 51 | .PARAMETER VMName 52 | The name of the Azure VM you want to remote into using PowerShell. The Get-AzureVM command 53 | can be used to view Azure VM names. 54 | .PARAMETER Secure 55 | If enabled, the secure switch will download and the VM's machine certifcate and install it 56 | in the local machine root store. When the -Secure parameter is not used, Setup-AzureRemotePS 57 | will add the VM FQDN to the local WinRM TrustedHosts list. 58 | To do: 59 | 60 | --Parameters should include 61 | Secure (requires downloading and installing PS self-signed certificate) or 62 | Unsecure (Use New-PSSessionOption to enable SkipCACheck and use the option 63 | with Enter-PSSession 64 | --Remove Verbose statements? 65 | #> 66 | #Requires -module Azure 67 | Param( 68 | [Parameter(Mandatory=$True)] 69 | [string]$cloudName, 70 | [string]$VMName, 71 | [switch]$Secure 72 | ) 73 | $VerbosePreference = "Continue" 74 | 75 | If((IsAdmin) -eq $false) 76 | { 77 | Write-Error "You must run PowerShell elevated to install WinRM certificates or modify Trusted Hosts." 78 | Return 79 | } 80 | 81 | # If we're not logged on to Azure, use Add-AzureAccount to log on 82 | 83 | If(-not (Get-AzureSubscription -ErrorAction SilentlyContinue)){ 84 | Add-AzureAccount 85 | } 86 | Select-AzureSubscription -SubscriptionName "MSDN Platforms" -Current 87 | $global:winRMURI = Get-AzureWinRMUri -ServiceName $cloudName -Name $VMName 88 | If($Secure){ 89 | InstallWinRMCertificateForVM -CloudServiceName $cloudName -Name $VMName 90 | }Else{ 91 | $originalTrustedHosts = (Get-Item WSMan:\localhost\Client\TrustedHosts).Value 92 | If($originalTrustedHosts){ 93 | Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$originalTrustedHosts,$cloudName.cloudapp.net" -Force 94 | }Else{ 95 | Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$cloudName.cloudapp.net" -Force 96 | } 97 | } 98 | $VerbosePreference = "SilentlyContinue" 99 | } 100 | 101 | Setup-AzureRemotePS -cloudName DatacenterImages -VMName JuneImage 102 | Enter-PSSession -ConnectionUri $winRMURI -Credential "JuneImage\shawn" -SessionOption (New-PSSessionOption -SkipCACheck) -------------------------------------------------------------------------------- /MorseCode.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [Parameter(Mandatory=$true)] 3 | [string]$message = 'SOS' 4 | ) 5 | 6 | $ditLength = 200 7 | $dashLength = $ditLength * 3 8 | $charSpace = $ditLength 9 | $letterSpace = $dashLength 10 | $wordSpace = $ditLength * 4 # because a word break (7 units) will always follow a letter break (3 units), we'll just add 4 units to the 3-unit letter break 11 | $frequency = 3000 12 | 13 | Function dit { 14 | [console]::Beep($frequency,$ditLength) 15 | } 16 | Function dash { 17 | [console]::Beep($frequency,$dashLength) 18 | } 19 | Function 1U { 20 | Start-Sleep -Milliseconds $charSpace 21 | } 22 | Function 3U { 23 | Start-Sleep -Milliseconds $letterSpace 24 | } 25 | Function 4U { 26 | Start-Sleep -Milliseconds $wordSpace 27 | } 28 | $messageWords = $message -split "\s+" 29 | ForEach ($word in $messageWords){ 30 | ForEach ($letter in ($word.ToCharArray())){ 31 | Switch ($letter) { 32 | "A" { 33 | dit 34 | 1U 35 | dash 36 | } 37 | "B" { 38 | dash 39 | 1U 40 | dit 41 | 1U 42 | dit 43 | 1U 44 | dit 45 | } 46 | "C" { 47 | dash 48 | 1U 49 | dit 50 | 1U 51 | dash 52 | 1U 53 | dit 54 | } 55 | "D" { 56 | dash 57 | 1U 58 | dit 59 | 1U 60 | dit 61 | 1U 62 | } 63 | "E" { 64 | dit 65 | } 66 | "F" { 67 | dit 68 | 1U 69 | dit 70 | 1U 71 | dash 72 | 1U 73 | dit 74 | } 75 | "G" { 76 | dash 77 | 1U 78 | dash 79 | 1U 80 | dit 81 | } 82 | "H" { 83 | dit 84 | 1U 85 | dit 86 | 1U 87 | dit 88 | 1U 89 | dit 90 | } 91 | "I" { 92 | dit 93 | 1U 94 | dit 95 | } 96 | "J" { 97 | dit 98 | 1U 99 | dash 100 | 1U 101 | dash 102 | 1U 103 | dash 104 | } 105 | "K" { 106 | dash 107 | 1U 108 | dit 109 | 1U 110 | dash 111 | } 112 | "L" { 113 | dit 114 | 1U 115 | dash 116 | 1U 117 | dit 118 | 1U 119 | dit 120 | } 121 | "M" { 122 | dash 123 | 1U 124 | dash 125 | } 126 | "N" { 127 | dash 128 | 1U 129 | dit 130 | } 131 | "O" { 132 | dash 133 | 1U 134 | dash 135 | 1U 136 | dash 137 | } 138 | "P" { 139 | dit 140 | 1U 141 | dash 142 | 1U 143 | dash 144 | 1U 145 | dit 146 | } 147 | "Q" { 148 | dash 149 | 1U 150 | dash 151 | 1U 152 | dit 153 | 1U 154 | dash 155 | } 156 | "R" { 157 | dit 158 | 1U 159 | dash 160 | 1U 161 | dit 162 | } 163 | "S" { 164 | dit 165 | 1U 166 | dit 167 | 1U 168 | dit 169 | } 170 | "T" { 171 | dash 172 | } 173 | "U" { 174 | dit 175 | 1U 176 | dit 177 | 1U 178 | dash 179 | } 180 | "V" { 181 | dit 182 | 1U 183 | dit 184 | 1U 185 | dit 186 | 1u 187 | dash 188 | } 189 | "W" { 190 | dit 191 | 1U 192 | dash 193 | 1U 194 | dash 195 | } 196 | "X" { 197 | dash 198 | 1U 199 | dit 200 | 1U 201 | dit 202 | 1u 203 | dash 204 | } 205 | "Y" { 206 | dash 207 | 1U 208 | dit 209 | 1U 210 | dash 211 | 1u 212 | dash 213 | } 214 | "Z" { 215 | dash 216 | 1U 217 | dash 218 | 1U 219 | dit 220 | 1U 221 | dit 222 | } 223 | 1 { 224 | dit 225 | 1U 226 | dash 227 | 1U 228 | dash 229 | 1U 230 | dash 231 | 1U 232 | dash 233 | } 234 | 2 { 235 | dit 236 | 1U 237 | dit 238 | 1U 239 | dash 240 | 1U 241 | dash 242 | 1U 243 | dash 244 | } 245 | 3 { 246 | dit 247 | 1U 248 | dit 249 | 1U 250 | dit 251 | 1U 252 | dash 253 | 1U 254 | dash 255 | } 256 | 4 { 257 | dit 258 | 1U 259 | dit 260 | 1U 261 | dit 262 | 1U 263 | dit 264 | 1U 265 | dash 266 | } 267 | 5 { 268 | dit 269 | 1U 270 | dit 271 | 1U 272 | dit 273 | 1U 274 | dit 275 | 1U 276 | dit 277 | } 278 | 6 { 279 | dash 280 | 1U 281 | dit 282 | 1U 283 | dit 284 | 1U 285 | dit 286 | 1U 287 | dit 288 | } 289 | 7 { 290 | dash 291 | 1U 292 | dash 293 | 1U 294 | dit 295 | 1U 296 | dit 297 | 1U 298 | dit 299 | } 300 | 8 { 301 | dash 302 | 1U 303 | dash 304 | 1U 305 | dash 306 | 1U 307 | dit 308 | 1U 309 | dit 310 | } 311 | 9 { 312 | dash 313 | 1U 314 | dash 315 | 1U 316 | dash 317 | 1U 318 | dash 319 | 1U 320 | dit 321 | } 322 | 0 { 323 | dash 324 | 1U 325 | dash 326 | 1U 327 | dash 328 | 1U 329 | dash 330 | 1U 331 | dash 332 | } 333 | } 334 | 3U #delay between letters 335 | } # End ForEach 336 | 4U # delay between words 337 | } # End ForEach -------------------------------------------------------------------------------- /ConvertToPGPWords.ps1: -------------------------------------------------------------------------------- 1 | Function ConvertTo-PgpWordString { 2 | # For example, the following command: 3 | # 'E582 94F2 E9A2 2748 6E8B 061B 31CC 528F D7FA 3F19' | ConvertTo-PgpWordString 4 | # should produce this output: 5 | # topmost Istanbul Pluto vagabond treadmill Pacific brackish dictator goldfish Medusa afflict bravado chatter revolver Dupont midsummer stopwatch whimsical cowbell bottomless 6 | 7 | [CmdletBinding()] 8 | Param( 9 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)] 10 | [string]$hexString 11 | ) 12 | Begin { 13 | $evenWords = 14 | "aardvark", "absurd", "accrue", "acme", "adrift", 15 | "adult", "afflict", "ahead", "aimless", "Algol", 16 | "allow", "alone", "ammo", "ancient", "apple", 17 | "artist", "assume", "Athens", "atlas", "Aztec", 18 | "baboon", "backfield", "backward", "banjo", "beaming", 19 | "bedlamp", "beehive", "beeswax", "befriend", "Belfast", 20 | "berserk", "billiard", "bison", "blackjack", "blockade", 21 | "blowtorch", "bluebird", "bombast", "bookshelf", "brackish", 22 | "breadline", "breakup", "brickyard", "briefcase", "Burbank", 23 | "button", "buzzard", "cement", "chairlift", "chatter", 24 | "checkup", "chisel", "choking", "chopper", "Christmas", 25 | "clamshell", "classic", "classroom", "cleanup", "clockwork", 26 | "cobra", "commence", "concert", "cowbell", "crackdown", 27 | "cranky", "crowfoot", "crucial", "crumpled", "crusade", 28 | "cubic", "dashboard", "deadbolt", "deckhand", "dogsled", 29 | "dragnet", "drainage", "dreadful", "drifter", "dropper", 30 | "drumbeat", "drunken", "Dupont", "dwelling", "eating", 31 | "edict", "egghead", "eightball", "endorse", "endow", 32 | "enlist", "erase", "escape", "exceed", "eyeglass", 33 | "eyetooth", "facial", "fallout", "flagpole", "flatfoot", 34 | "flytrap", "fracture", "framework", "freedom", "frighten", 35 | "gazelle", "Geiger", "glitter", "glucose", "goggles", 36 | "goldfish", "gremlin", "guidance", "hamlet", "highchair", 37 | "hockey", "indoors", "indulge", "inverse", "involve", 38 | "island", "jawbone", "keyboard", "kickoff", "kiwi", 39 | "klaxon", "locale", "lockup", "merit", "minnow", 40 | "miser", "Mohawk", "mural", "music", "necklace", 41 | "Neptune", "newborn", "nightbird", "Oakland", "obtuse", 42 | "offload", "optic", "orca", "payday", "peachy", 43 | "pheasant", "physique", "playhouse", "Pluto", "preclude", 44 | "prefer", "preshrunk", "printer", "prowler", "pupil", 45 | "puppy", "python", "quadrant", "quiver", "quota", 46 | "ragtime", "ratchet", "rebirth", "reform", "regain", 47 | "reindeer", "rematch", "repay", "retouch", "revenge", 48 | "reward", "rhythm", "ribcage", "ringbolt", "robust", 49 | "rocker", "ruffled", "sailboat", "sawdust", "scallion", 50 | "scenic", "scorecard", "Scotland", "seabird", "select", 51 | "sentence", "shadow", "shamrock", "showgirl", "skullcap", 52 | "skydive", "slingshot", "slowdown", "snapline", "snapshot", 53 | "snowcap", "snowslide", "solo", "southward", "soybean", 54 | "spaniel", "spearhead", "spellbind", "spheroid", "spigot", 55 | "spindle", "spyglass", "stagehand", "stagnate", "stairway", 56 | "standard", "stapler", "steamship", "sterling", "stockman", 57 | "stopwatch", "stormy", "sugar", "surmount", "suspense", 58 | "sweatband", "swelter", "tactics", "talon", "tapeworm", 59 | "tempest", "tiger", "tissue", "tonic", "topmost", 60 | "tracker", "transit", "trauma", "treadmill", "Trojan", 61 | "trouble", "tumor", "tunnel", "tycoon", "uncut", 62 | "unearth", "unwind", "uproot", "upset", "upshot", 63 | "vapor", "village", "virus", "Vulcan", "waffle", 64 | "wallet", "watchword", "wayside", "willow", "woodlark", 65 | "Zulu" 66 | 67 | $oddWords = 68 | "adroitness", "adviser", "aftermath", "aggregate", "alkali", 69 | "almighty", "amulet", "amusement", "antenna", "applicant", 70 | "Apollo", "armistice", "article", "asteroid", "Atlantic", 71 | "atmosphere", "autopsy", "Babylon", "backwater", "barbecue", 72 | "belowground", "bifocals", "bodyguard", "bookseller", 73 | "borderline", "bottomless", "Bradbury", "bravado", 74 | "Brazilian", "breakaway", "Burlington", "businessman", 75 | "butterfat", "Camelot", "candidate", "cannonball", 76 | "Capricorn", "caravan", "caretaker", "celebrate", 77 | "cellulose", "certify", "chambermaid", "Cherokee", 78 | "Chicago", "clergyman", "coherence", "combustion", 79 | "commando", "company", "component", "concurrent", 80 | "confidence", "conformist", "congregate", "consensus", 81 | "consulting", "corporate", "corrosion", "councilman", 82 | "crossover", "crucifix", "cumbersome", "customer", "Dakota", 83 | "decadence", "December", "decimal", "designing", "detector", 84 | "detergent", "determine", "dictator", "dinosaur", 85 | "direction", "disable", "disbelief", "disruptive", 86 | "distortion", "document", "embezzle", "enchanting", 87 | "enrollment", "enterprise", "equation", "equipment", 88 | "escapade", "Eskimo", "everyday", "examine", "existence", 89 | "exodus", "fascinate", "filament", "finicky", "forever", 90 | "fortitude", "frequency", "gadgetry", "Galveston", 91 | "getaway", "glossary", "gossamer", "graduate", "gravity", 92 | "guitarist", "hamburger", "Hamilton", "handiwork", 93 | "hazardous", "headwaters", "hemisphere", "hesitate", 94 | "hideaway", "holiness", "hurricane", "hydraulic", 95 | "impartial", "impetus", "inception", "indigo", "inertia", 96 | "infancy", "inferno", "informant", "insincere", "insurgent", 97 | "integrate", "intention", "inventive", "Istanbul", 98 | "Jamaica", "Jupiter", "leprosy", "letterhead", "liberty", 99 | "maritime", "matchmaker", "maverick", "Medusa", "megaton", 100 | "microscope", "microwave", "midsummer", "millionaire", 101 | "miracle", "misnomer", "molasses", "molecule", "Montana", 102 | "monument", "mosquito", "narrative", "nebula", "newsletter", 103 | "Norwegian", "October", "Ohio", "onlooker", "opulent", 104 | "Orlando", "outfielder", "Pacific", "pandemic", "Pandora", 105 | "paperweight", "paragon", "paragraph", "paramount", 106 | "passenger", "pedigree", "Pegasus", "penetrate", 107 | "perceptive", "performance", "pharmacy", "phonetic", 108 | "photograph", "pioneer", "pocketful", "politeness", 109 | "positive", "potato", "processor", "provincial", 110 | "proximate", "puberty", "publisher", "pyramid", "quantity", 111 | "racketeer", "rebellion", "recipe", "recover", "repellent", 112 | "replica", "reproduce", "resistor", "responsive", 113 | "retraction", "retrieval", "retrospect", "revenue", 114 | "revival", "revolver", "sandalwood", "sardonic", "Saturday", 115 | "savagery", "scavenger", "sensation", "sociable", 116 | "souvenir", "specialist", "speculate", "stethoscope", 117 | "stupendous", "supportive", "surrender", "suspicious", 118 | "sympathy", "tambourine", "telephone", "therapist", 119 | "tobacco", "tolerance", "tomorrow", "torpedo", "tradition", 120 | "travesty", "trombonist", "truncated", "typewriter", 121 | "ultimate", "undaunted", "underfoot", "unicorn", "unify", 122 | "universe", "unravel", "upcoming", "vacancy", "vagabond", 123 | "vertigo", "Virginia", "visitor", "vocalist", "voyager", 124 | "warranty", "Waterloo", "whimsical", "Wichita", 125 | "Wilmington", "Wyoming", "yesteryear", "Yucatan" 126 | 127 | Function Clean-Hex { 128 | Param( 129 | [parameter(Mandatory=$true)] 130 | [string]$hexString 131 | ) 132 | $hexString = $hexString -replace "\s+","" 133 | $hexString = $hexString -replace "-","" 134 | $hexString = $hexString -replace ":","" 135 | $hexString = $hexString -replace "`n","" 136 | Write-Output $hexString 137 | } 138 | 139 | Function Convert-HexToByteArray { 140 | [cmdletbinding()] 141 | param( 142 | [parameter(Mandatory=$true)] 143 | [string]$hexString 144 | ) 145 | # create an empty byte array 146 | $bytes = [byte[]]::new($hexString.Length / 2) 147 | 148 | For($i=0; $i -lt $hexString.Length; $i+=2){ 149 | $bytes[$i/2] = [convert]::ToByte($HexString.Substring($i, 2), 16) 150 | } 151 | Write-Output $bytes 152 | } 153 | } # end Begin block 154 | 155 | Process { 156 | $byteArray = Convert-HexToByteArray -hexString (Clean-Hex $hexString) 157 | $wordArray = @() 158 | 159 | For($i = 0;$i -lt $byteArray.Count;$i++){ 160 | If($i % 2){ 161 | $wordArray += $oddWords[$byteArray[$i]] 162 | }Else{ 163 | $wordArray += $evenWords[$byteArray[$i]] 164 | } 165 | } 166 | $wordArray -join " " 167 | } # end Process block 168 | } --------------------------------------------------------------------------------