├── Blink1-RestMethods.ps1 ├── DNSSec_v0.2.ps1 ├── DSC └── Scripts │ └── cBgInfo │ ├── SourceFiles │ ├── Bginfo.exe.lnk │ ├── ReadMe.txt │ └── default.bgi │ └── cBgInfoExample.ps1 ├── Examples ├── 4_CreateOM12ServiceAccountsConfigData.psd1 ├── Attach_OMSetup_vhd.ps1 ├── CheckForNewModules.ps1 ├── CompareGetHelp.ps1 ├── CompareObjectOGV.ps1 ├── CopyToUSB.ps1 ├── CreateWinForm_0.1.ps1 ├── DSC_CreateOM12ServiceAccounts.ps1 ├── DemoLogicalOperators.ps1 ├── DscClassISESnippet.ps1 ├── DscClassISESnippetCode.ps1 ├── ExportBitlocker.ps1 ├── FastSealWrapper.ps1 ├── Find-Package-Project-Website.ps1 ├── FunWithDynamicParams.ps1 ├── Get-MPWiki-ConvertFromString.ps1 ├── Get-MPWiki.ps1 ├── ISEAdOn_Example.ps1 ├── ISESteroids_Context-Menu_BackTicks.ps1 ├── InstallBoot2DockerOnHyperV.ps1 ├── InstallDSCResourceWave8.ps1 ├── InstallMinecraftinContainer.ps1 ├── MSBand_v0.1.ps1 ├── ObjectConceptsExplained_v0.2.ps1 ├── Ping-IPRange.ps1 ├── ProblemStepRecorder.ps1 ├── RunbookAutomation.ps1 ├── ScriptExplorerGUI.ps1 ├── ScriptHeader.ps1 ├── SuspendPowerPlan.ps1 ├── Test-IEFavorite.ps1 ├── Test-PrimeNumber.ps1 ├── ThankYou.ps1 ├── Top2000.ps1 ├── WinMerge.ps1 ├── convert-image2text.ps1 └── test.gitje ├── Get-TweetTimeline.ps1 ├── Get-WebCamp.ps1 ├── NetflixHack.ps1 ├── Pebble_v0.1.ps1 ├── README.md ├── TrackDHL.ps1 ├── WLANProfiles.ps1 ├── WinKeys.ps1 └── WinMergeISEAddOn ├── Module └── ISEWinMerge │ ├── ISEWinMerge.psd1 │ └── ISEWinMerge.psm1 ├── README.md ├── WINMerge_WPF.ps1 ├── WinMerge-ISEAddOn.ps1 ├── WinMergeWPF_opt.gif └── isewinmergemodule.gif /Blink1-RestMethods.ps1: -------------------------------------------------------------------------------- 1 | #'http://localhost:8934/blink1/pattern/add?pname=policeflash&pattern=0,%23ff0000,0.5,%230000ff,0.5' 2 | #create pattern 3 | 4 | invoke-WebRequest -Uri 'http://localhost:8934/blink1/pattern/add?pname=blink3green&pattern=3,%2300ff00,1.5,%23000000,0.5' 5 | 6 | 7 | #Play Pattern 8 | #'http://localhost:8934/blink1/pattern/play?pname=policeflash' 9 | $url = "http://localhost:8934/blink1/pattern/play?pname=blink3green" 10 | invoke-WebRequest -Uri $url 11 | 12 | #Turn Pattern off 13 | invoke-WebRequest -Uri 'http://localhost:8934/blink1/pattern/stop?pname=policeflash' 14 | 15 | #Get Patterns 16 | Invoke-RestMethod -Uri "http://localhost:8934/blink1/patterns" | select -ExpandProperty patterns 17 | 18 | 19 | #Turn off 20 | Invoke-RestMethod -Uri "http://localhost:8934/blink1/off" 21 | 22 | #Get Blink1 ID 23 | Invoke-RestMethod -Uri "http://localhost:8934/blink1/id" 24 | 25 | #FadeToRGB 26 | Invoke-RestMethod -Uri "http://localhost:8934/blink1/fadeToRGB" 27 | 28 | invoke-WebRequest -Uri 'http://localhost:8934/blink1/fadeToRGB' 29 | 30 | #Call Color Picker Copy Pattern 31 | $patterns = Invoke-RestMethod -Uri "http://localhost:8934/blink1/patterns" | select -ExpandProperty patterns 32 | invoke-WebRequest -Uri "http://localhost:8934/blink1/pattern/play?pname=$($patterns.name[0])" 33 | 34 | #Set Blink1 Color 35 | invoke-WebRequest -Uri "http://localhost:8934/blink1/fadeToRGB?rgb=%23ffcc00" #white 36 | 37 | #Fade in 1 sec to 0000FF colour 38 | invoke-WebRequest -Uri "http://localhost:8934/blink1/fadeToRGB?rgb=%230000FF&time=1.0" 39 | 40 | invoke-WebRequest -Uri "http://localhost:8934/blink1/fadeToRGB?rgb=%23ff0000" #red 41 | 42 | #Foo-Bar does not work 43 | #Invoke-RestMethod -Uri "http://localhost:8934/blink1/foo%2Fbar" 44 | 45 | #Random RGB Creator 46 | (1..3 | Foreach {[string](Get-Random -Maximum 255)} | join-string -Separator " ").replace(" ",",") 47 | 48 | #HEx 49 | (1..3 | Foreach {[string](Get-Random -Maximum 255)} | % {"{0:x}" -f $_} | join-string -Separator " ").replace(" ",",") 50 | 51 | 0,0,0 | % {"{0:x}" -f $_} 52 | 53 | 54 | #"{0:x}" -f 250 55 | 56 | 57 | # Let's create "blink3green" = "blink green 3 times, 1.5 secs on, 0.5 secs off". 58 | # 'http://localhost:8934/blink1/pattern/add?pname=blink3green&pattern=3,%2300ff00,1.5,%23000000,0.5' 59 | # "http://localhost:8934/blink1/pattern/add?pname=blink3redgreenoff&pattern=3,#FF312F,0.50,#24FF20,0.50,#000000,0.50" 60 | Invoke-WebRequest -Uri "http://localhost:8934/blink1/pattern/add?pname=blink3redgreenoff&pattern=3,%23FF312F,0.50,%2324FF20,0.50,%23000000,0.50" 61 | 62 | Function Set-Blink1Pattern ($name,$repeat=0,$time,$colorinhex) 63 | { 64 | $body = "pname=$name&pattern=$repeat,%23$colorinhex,$time,%230000ff,0.5" 65 | invoke-WebRequest -Uri "http://localhost:8934/blink1/pattern/add?$body" 66 | } 67 | 68 | #Set-Blink1Pattern -Name Test -Repeat 3 -Time 1.5 -colorinhex 00ff00 69 | 70 | 71 | Function Start-Blink1Pattern ($name) 72 | { 73 | invoke-WebRequest -Uri "http://localhost:8934/blink1/pattern/play?pname=$($name)" 74 | } 75 | 76 | Function Stop-Blink1Pattern ($name) 77 | { 78 | invoke-WebRequest -Uri "http://localhost:8934/blink1/pattern/stop?pname=$($name)" 79 | } 80 | 81 | Function Get-Blink1Pattern 82 | { 83 | Invoke-RestMethod -Uri "http://localhost:8934/blink1/patterns" | select -ExpandProperty patterns 84 | } 85 | 86 | 87 | #Start-Blink1Pattern -name Test 88 | 89 | Function Stop-Blink1 90 | { 91 | Invoke-RestMethod -Uri "http://localhost:8934/blink1/off" 92 | } 93 | 94 | Function Get-Blink1Id 95 | { 96 | Invoke-RestMethod -Uri "http://localhost:8934/blink1/id" 97 | } 98 | 99 | Function Get-Blink1IFTTT 100 | { 101 | $ifttt = Invoke-RestMethod "http://api.thingm.com/blink1/events/{code} 102 | 103 | $ifttt.events | select blink1_id, name, source, @{L="Date";E={[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($ifttt.events.date))}} 104 | } 105 | 106 | 107 | #When trigger is tested every 15 mins the last date time should be greater then current time minus 15 minutes. 108 | #((Get-Blink1IFTTT).date -gt (get-date).AddMinutes(-15)) 109 | 110 | While ($true) 111 | { 112 | 113 | if (((Get-Blink1IFTTT).Name -eq "TestBlink1") -and ((Get-Blink1IFTTT).date -lt (get-date).AddMinutes(-15)) ){Start-Blink1Pattern -Name blink3redgreenoff | Out-Null} 114 | sleep 60 115 | } 116 | 117 | 118 | $script = {while ($true){invoke-WebRequest -Uri "http://localhost:8934/blink1/pattern/play?pname=TestBlink1IFTTT";sleep 10}} 119 | 120 | $blink1job = Start-Job -Name Test2 -ScriptBlock $script 121 | 122 | $Blink1IFTTTJob = Start-Job -Name Blink1IFTTT -ScriptBlock {while ($true){if (((Get-Blink1IFTTT).Name -eq "TestBlink1") -and ((Get-Blink1IFTTT).date -lt (get-date).AddMinutes(-15)) ){Start-Blink1Pattern -Name blink3redgreenoff};sleep 60}} 123 | 124 | $job = Start-Job -ScriptBlock {while ($true){Get-Blink1IFTTT;sleep 60}} 125 | Receive-Job -Job $job 126 | 127 | $testJob = Start-Job -Name Test -ScriptBlock {while ($true){Get-Process;sleep 60}} 128 | 129 | Function Get-RandomColor 130 | { 131 | $count = [Enum]::GetValues([System.Drawing.KnownColor]).Count 132 | $randomcolor = [System.Drawing.KnownColor](Get-Random -Minimum 1 -Maximum $count) 133 | [System.Drawing.Color]::FromKnownColor($randomcolor) 134 | } 135 | 136 | 137 | -------------------------------------------------------------------------------- /DNSSec_v0.2.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | DNSSec Debugger using Verisign webpage 4 | .DESCRIPTION 5 | The DNSSEC Debugger is a Web-based tool for ensuring that the "chain of trust" is intact for a particular DNSSEC enabled domain name. 6 | The tool shows a step-by-step validation of a given domain name and highlights any problems found. 7 | .EXAMPLE 8 | Test-DNSSec -DomainName www.verisign.com 9 | .EXAMPLE 10 | Test-DNSSec -DomainName www.stranger.nl 11 | .LINK 12 | http://dnssec-debugger.verisignlabs.com/ 13 | #> 14 | function Test-Dnssec 15 | { 16 | [CmdletBinding()] 17 | Param 18 | ( 19 | # Param1 help description 20 | [Parameter(Mandatory=$true, 21 | Position=0)] 22 | $DomainName 23 | ) 24 | 25 | $url = "http://dnssec-debugger.verisignlabs.com/$DomainName" 26 | 27 | $result = Invoke-WebRequest $URL 28 | 29 | $result.ParsedHtml.getElementsByTagName("tr") | 30 | Where-Object "classname" -match "^L0" | 31 | Select-Object -ExpandProperty InnerText | 32 | ForEach-Object {if ($_ -match "^No") 33 | { 34 | write-host $_ -ForegroundColor red 35 | } 36 | else 37 | { 38 | Write-Host $_ 39 | } 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /DSC/Scripts/cBgInfo/SourceFiles/Bginfo.exe.lnk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanstranger/PowerShell/39abaa832c2108b716c506765d532188df8e3e55/DSC/Scripts/cBgInfo/SourceFiles/Bginfo.exe.lnk -------------------------------------------------------------------------------- /DSC/Scripts/cBgInfo/SourceFiles/ReadMe.txt: -------------------------------------------------------------------------------- 1 | Download BgInfo.zip from http://technet.microsoft.com/en-us/sysinternals/bb897557.aspx and put in this location. -------------------------------------------------------------------------------- /DSC/Scripts/cBgInfo/SourceFiles/default.bgi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanstranger/PowerShell/39abaa832c2108b716c506765d532188df8e3e55/DSC/Scripts/cBgInfo/SourceFiles/default.bgi -------------------------------------------------------------------------------- /DSC/Scripts/cBgInfo/cBgInfoExample.ps1: -------------------------------------------------------------------------------- 1 | #Requires -RunAsAdministrator 2 | # --------------------------------------------------- 3 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\DSC\Resources\cBgInfo\cBgInfoExample.ps1 4 | # Version: 0.1 5 | # Author: Stefan Stranger 6 | # Date: 03/08/2014 16:30:17 7 | # Description: Installs SysInternals tool BgInfo and created a shortcut in Startup menu 8 | # Comments: You first need to download the BgInfo.zip file from: http://technet.microsoft.com/en-us/sysinternals/bb897557.aspx 9 | # Secondly you need to create a BgInfo Configuration File (default.bgi) and a shortcut file to BgInfo with the following configuration. 10 | # Target: "C:\Program Files\BgInfo\Bginfo.exe" default.bgi /timer:0 /NOLICPROMPT 11 | # This DSC Script executes 3 steps. 12 | # 1. Unzips the BgInfo.zip to "C:\Program Files\BgInfo" folder. 13 | # 2. Copies pre-created BgInfo info config file (default.bgi) to C:\Program Files\BgInfo folder 14 | # 3. Copies pre-configured BgInfo Shortcut file to "C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" folder 15 | # Disclamer: Note that this is provided “AS-IS” with no warranties at all. This is not a production ready solution, just an idea and an example. 16 | # --------------------------------------------------- 17 | 18 | Configuration BgInfoZipConfig 19 | { 20 | param ([Parameter(Mandatory=$true)] 21 | [string]$SourcePath, 22 | [Parameter(Mandatory)] 23 | [string]$DestinationPath, 24 | [string]$computername="localhost") 25 | 26 | 27 | Node ($computername) 28 | { 29 | 30 | Archive cBgInfoZip { 31 | Ensure = "Present" 32 | Path = "$SourcePath\BgInfo.zip" 33 | Destination = "$DestinationPath" 34 | Force = $True 35 | } 36 | 37 | } 38 | } 39 | 40 | $SourcePath = "C:\Users\stefstr\Documents\GitHub\PowerShell\DSC\Scripts\cBgInfo\SourceFiles" 41 | $DestinationPath = "C:\Program Files\BgInfo" 42 | 43 | 44 | BgInfoZipConfig -SourcePath $SourcePath -DestinationPath $DestinationPath -computername $($env:computername) -OutputPath "$Env:Temp\BgInfoConfig" 45 | Start-DscConfiguration -Path "$Env:Temp\BgInfoConfig" -Wait -Force -Verbose -ErrorAction Continue 46 | 47 | 48 | #Copy default.bgi file 49 | 50 | Configuration BgInfoFileCopyConfig 51 | { 52 | param( 53 | [parameter(Mandatory)] 54 | [string]$SourceFilePath, 55 | [parameter(Mandatory=$true)] 56 | [string]$DestinationPath, 57 | [string]$ComputerName 58 | ) 59 | 60 | Node ($ComputerName) 61 | { 62 | File DirectoryCopy 63 | { 64 | Ensure = "Present" # You can also set Ensure to "Absent" 65 | Type = "File" # Default is "File". 66 | Recurse = $false # Ensure presence of subdirectories, too 67 | SourcePath = "$SourceFilePath\default.bgi" 68 | DestinationPath = $DestinationPath 69 | } 70 | 71 | Log AfterFileCopy 72 | { 73 | # The message below gets written to the Microsoft-Windows-Desired State Configuration/Analytic log 74 | Message = "Finished running the file resource with ID DirectoryCopy" 75 | DependsOn = "[File]DirectoryCopy" # This means run "DirectoryCopy" first. 76 | } 77 | } 78 | } 79 | 80 | $SourceFilePath = "C:\Users\stefstr\Documents\GitHub\PowerShell\DSC\Scripts\cBgInfo\SourceFiles" 81 | $DestinationPath = "C:\Program Files\BgInfo" 82 | 83 | BgInfoFileCopyConfig -SourceFilePath $SourceFilePath -DestinationPath $DestinationPath -computername $($env:computername) -OutputPath "$Env:Temp\BgInfoFileCopyConfig" 84 | Start-DscConfiguration -Path "$Env:Temp\BgInfoFileCopyConfig" -Wait -Force -Verbose -ErrorAction Continue 85 | 86 | #Copy shortcut to C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 87 | 88 | Configuration BgInfoShortCutCopyConfig 89 | { 90 | param( 91 | [parameter(Mandatory)] 92 | [string]$SourceFilePath, 93 | [parameter(Mandatory=$true)] 94 | [string]$DestinationPath, 95 | [string]$ComputerName 96 | ) 97 | 98 | Node ($ComputerName) 99 | { 100 | File DirectoryCopy 101 | { 102 | Ensure = "Present" # You can also set Ensure to "Absent" 103 | Type = "File" # Default is "File". 104 | Recurse = $false # Ensure presence of subdirectories, too 105 | SourcePath = "$SourceFilePath\Bginfo.exe.lnk" 106 | DestinationPath = $DestinationPath 107 | } 108 | 109 | Log AfterFileCopy 110 | { 111 | # The message below gets written to the Microsoft-Windows-Desired State Configuration/Analytic log 112 | Message = "Finished running the file resource with ID DirectoryCopy" 113 | DependsOn = "[File]DirectoryCopy" # This means run "DirectoryCopy" first. 114 | } 115 | } 116 | } 117 | 118 | $SourceFilePath = "C:\Users\stefstr\Documents\GitHub\PowerShell\DSC\Scripts\cBgInfo\SourceFiles" 119 | $DestinationPath = "C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" 120 | 121 | BgInfoShortCutCopyConfig -SourceFilePath $SourceFilePath -DestinationPath $DestinationPath -computername $($env:computername) -OutputPath "$Env:Temp\BgInfoShortCutCopyConfig" 122 | Start-DscConfiguration -Path "$Env:Temp\BgInfoShortCutCopyConfig" -Wait -Force -Verbose -ErrorAction Continue -------------------------------------------------------------------------------- /Examples/4_CreateOM12ServiceAccountsConfigData.psd1: -------------------------------------------------------------------------------- 1 | # Environment Configuration 2 | # Environmental configuration defines the environment in which the configuration is deployed. 3 | # For instance, the node names and source file locations can change from a development to a test to a production environment 4 | @{ 5 | AllNodes = @( 6 | @{ 7 | Nodename = "OM12R2DSC-DC" 8 | Role = "Primary DC" 9 | DomainName = "dsc.contoso.com" 10 | PSDscAllowPlainTextPassword = $true 11 | Users = @( 12 | @{ 13 | UserName = "om_saa" 14 | } 15 | @{ 16 | UserName = "om_das" 17 | } 18 | @{ 19 | UserName = "om_dra" 20 | } 21 | @{ 22 | UserName = "om_dwa" 23 | } 24 | @{ 25 | UserName = "installer" 26 | } 27 | 28 | ) 29 | GroupName = "Domain Admins" 30 | Members = @('om_saa','om_das','om_dra','om_dwa','installer') 31 | 32 | } 33 | ) 34 | } 35 | -------------------------------------------------------------------------------- /Examples/Attach_OMSetup_vhd.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Scripts\PS\Azure\Attach_OMSetup_vhd.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 02/05/2015 15:26:30 6 | # Description: Create a local vhd, insert an iso file and upload to azure storage container and attach vhd to VM 7 | # Comments: 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | 15 | #Variables: 16 | $vhdpath = "d:\vhds\OMSetup.vhd" 17 | $destinationVHD = "https://mystorage.blob.core.windows.net/opsmgr/opsmgrsetup.vhd" 18 | $size = 1GB 19 | $isopath = "D:\ISOs\en_system_center_2012_r2_operations_manager_x86_and_x64_dvd_2920299.iso" 20 | 21 | #Create VHD 22 | #Mount VHD 23 | #Intialize Disk 24 | #Create partition 25 | #Format Volume 26 | New-VHD -path $vhdpath -SizeBytes $size -Dynamic 27 | Mount-VHD -Path $vhdpath 28 | Get-Disk -FriendlyName "Microsoft Virtual Disk" | 29 | Initialize-Disk -PartitionStyle MBR -PassThru | 30 | New-Partition -UseMaximumSize -AssignDriveLetter:$False -MbrType IFS | 31 | Format-Volume -Confirm:$false -FileSystem NTFS -force | 32 | get-partition | Add-PartitionAccessPath -AssignDriveLetter -PassThru 33 | 34 | #Copy OMSetup.iso to mounted disk 35 | $Driveletter = (Get-Disk -FriendlyName "Microsoft Virtual Disk" | get-partition) 36 | $Destination = $Driveletter.DriveLetter+":" 37 | copy-item -path $isopath -Destination $Destination 38 | 39 | #Dismount vhd 40 | Dismount-VHD $VHDPath 41 | 42 | 43 | #load Azure module 44 | Import-Module Azure 45 | 46 | #Authenticate through Windows Azure Active Directory and downloads associated subscriptions 47 | Add-AzureAccount 48 | 49 | #Upload vhd 50 | Add-AzureVhd -LocalFilePath $vhdpath -Destination $destinationVHD -NumberOfUploaderThreads 5 51 | 52 | 53 | # Adds a new disk to the Microsoft Azure disk repository. 54 | Add-AzureDisk -DiskName "OMSetup" -MediaLocation $destinationVHD -Label "OMSetup" 55 | 56 | #Attach disk to VM 57 | Get-AzureVM -service "service" -Name "vm" | Add-AzureDataDisk -Import -DiskName "OMsetup" -LUN 0 | Update-AzureVM 58 | 59 | -------------------------------------------------------------------------------- /Examples/CheckForNewModules.ps1: -------------------------------------------------------------------------------- 1 | #requires -Version 3 -Modules PowerShellGet 2 | 3 | # --------------------------------------------------- 4 | # Script: C:\Users\stefstr\OneDrive - Microsoft\Scripts\PS\CheckForNewModules.ps1 5 | # Version: 0.1 6 | # Author: Stefan Stranger 7 | # Date: 02/22/2016 11:33:31 8 | # Description: Check for Module Updates on PSGallery 9 | # Comments: Idea from Øyvind Kallstad 10 | # Changes: 11 | # Disclaimer: 12 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 13 | # **Always test in your lab first** Do this at your own risk!! 14 | # The author will not be held responsible for any damage you incur when making these changes! 15 | # --------------------------------------------------- 16 | 17 | Workflow Check-Module 18 | { 19 | $AllModules = Get-Module -ListAvailable 20 | foreach -parallel ($module in $AllModules) 21 | { 22 | $foundModule = Find-Module -Name $module.Name -ErrorAction SilentlyContinue 23 | if ($foundModule) 24 | { 25 | if ($module.Version -lt $foundModule.Version) 26 | { 27 | "Update found for $($module.name) with version $($module.Version)" 28 | } 29 | } 30 | } 31 | } 32 | 33 | Check-Module -AsJob -JobName wfmodule 34 | 35 | #Get-Job -name wfmodule | receive-job -keep 36 | -------------------------------------------------------------------------------- /Examples/CompareGetHelp.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\CompareGetHelp.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 03/02/2015 15:45:03 6 | # Description: Compare different Get-Help parameters. 7 | # Comments: 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | get-help dir | out-string -OutVariable helptext | out-null 15 | get-help dir -full | out-string -OutVariable helptextfull | out-null 16 | 17 | compare-object (([regex]::matches($helptext, "\b[A-Z]+") | 18 | %{if ($_.value.length -gt 3){$_.value}}) | 19 | select -Unique) (([regex]::matches($helptextfull, "\b[A-Z]+") | 20 | %{if ($_.value.length -gt 3){$_.value}}) | 21 | select -Unique) -IncludeEqual 22 | 23 | -------------------------------------------------------------------------------- /Examples/CompareObjectOGV.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\Stefan\Documents\GitHub\PowerShell\Examples\CompareObjectOGV.ps1 3 | # Tags: compare, PowerShell, GUI 4 | # Version: 0.1 5 | # Author: Stefan Stranger 6 | # Date: 08/26/2016 15:19:03 7 | # Description: Compare objects example 8 | # Comments: 9 | # Changes: 10 | # Disclaimer: 11 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 12 | # **Always test in your lab first** Do this at your own risk!! 13 | # The author will not be held responsible for any damage you incur when making these changes! 14 | # --------------------------------------------------- 15 | 16 | get-random -InputObject @(1..10) -Count 5 -OutVariable ref 17 | 18 | get-random -InputObject @(1..10) -Count 5 -OutVariable dif 19 | 20 | compare-object -ReferenceObject $ref -DifferenceObject $dif -IncludeEqual 21 | 22 | 23 | compare-object -ReferenceObject $ref -DifferenceObject $dif -IncludeEqual | 24 | select @{l='ReferecencObject';e={if ($_.SideIndicator -eq '==' -or $_.SideIndicator -eq '<=' ) {$($_.InputObject)}}}, 25 | @{l='DifferenceObject';e={if ($_.SideIndicator -eq '==' -or $_.SideIndicator -eq '=>' ) {$($_.InputObject)}}} | ogv -PassThru -------------------------------------------------------------------------------- /Examples/CopyToUSB.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Scripts\PS\CopyToUSB.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 09/24/2015 19:12:12 6 | # Description: Copy file when USB is inserted 7 | # Comments: Idea from Trevor Sullivan @pcgeek86 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | 15 | $CopystuffToUSB = { 16 | #Get info about inserted USB stick 17 | $wmiquery = 'select * from win32_logicaldisk where drivetype = 2' 18 | $usb = Get-WmiObject -namespace root\cimv2 -query $wmiquery 19 | 20 | #Check if USB has Filesystem of fat if not do not copy files 21 | if ($usb.FileSystem -eq 'FAT32') { 22 | 23 | 24 | Write-Host -Object ('New USB Drive inserted in drive: {0}' -f $usb.deviceid) 25 | 26 | 27 | # Copy the object to the appropriate folder within the destination folder 28 | Copy-Item -Path 'C:\temp\USB_Part1.zip' -Destination $usb.DeviceID 29 | 30 | 31 | } 32 | 33 | } 34 | 35 | $EventQuery = 'Select * from __InstanceCreationEvent within 5 36 | where TargetInstance ISA ''Win32_LogicalDisk'' and TargetInstance.DriveType = 2'; 37 | 38 | 39 | Get-EventSubscriber | Unregister-Event; 40 | Register-WmiEvent -Query $EventQuery -Action $CopystuffToUSB -SourceIdentifier USBStick 41 | 42 | 43 | #Register-WmiEvent -Query $EventQuery -SourceIdentifier USBStick 44 | 45 | #Get-WmiObject -Query $EventQuery 46 | $wmiquery = 'select * from win32_logicaldisk where drivetype = 2' 47 | $usb = Get-WmiObject -namespace root\cimv2 -query $wmiquery 48 | $usb | fl * 49 | -------------------------------------------------------------------------------- /Examples/CreateWinForm_0.1.ps1: -------------------------------------------------------------------------------- 1 | #Create winform 2 | #Assemblies 3 | $assemblies = @' 4 | #region Import the Assemblies 5 | [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null 6 | [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null 7 | #endregion 8 | '@ 9 | 10 | #$assemblies 11 | #End Assemblies 12 | 13 | #Empty variables 14 | $code,$tabs,$checkboxes,$displaynames,$ifstatements, $switchs, $counter = $null 15 | 16 | #Objects 17 | #Add checkbox object for each open ISE tab 18 | $Checkboxes = $null 19 | $tabs = $PSISe.PowerShellTabs.Files 20 | foreach ($tab in $tabs) 21 | { 22 | #remove non ascii characters 23 | $displayname = ($tab.Displayname) -creplace '[^a-zA-Z0-9]', '' 24 | $Checkboxes += '$' + $displayname + " = New-Object System.Windows.Forms.CheckBox; `n" 25 | } 26 | 27 | #$Checkboxes 28 | 29 | $objects = @" 30 | #region Generated Form Objects 31 | `$form1 = New-Object System.Windows.Forms.Form 32 | $checkboxes 33 | `$button2 = New-Object System.Windows.Forms.Button 34 | `$button1 = New-Object System.Windows.Forms.Button 35 | `$label1 = New-Object System.Windows.Forms.Label 36 | `$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState 37 | #endregion Generated Form Objects 38 | "@ 39 | 40 | #$objects 41 | #End Objects 42 | 43 | #Code 44 | $displaynames = @() 45 | foreach ($tab in $tabs) 46 | { 47 | $displayname = ($tab.Displayname) -creplace '[^a-zA-Z0-9]', '' 48 | $displaynames += '$' + $displayname 49 | $Checkboxes += '$' + ($tab.Displayname).Replace(" ","") + " = New-Object System.Windows.Forms.CheckBox; `n" 50 | } 51 | 52 | foreach ($tab in $tabs) 53 | { 54 | $displayname = ($tab.Displayname) -creplace '[^a-zA-Z0-9]', '' 55 | 56 | $ifstatement = @" 57 | if (`$$($displayname).checked){`$numberofselectedcheckboxes++} 58 | "@ 59 | 60 | [string]$ifstatements += "$ifstatement `n" 61 | } 62 | 63 | 64 | foreach ($tab in $tabs) 65 | { 66 | $displayname = ($tab.Displayname) -creplace '[^a-zA-Z0-9]', '' 67 | $switch = @" `$$displayname 68 | "@ 69 | [string]$switchs += $switch + "," 70 | } 71 | 72 | $switchs = $switchs.Substring(0,$switchs.Length-1) 73 | 74 | $counter = 0 75 | foreach ($tab in $tabs) 76 | { 77 | 78 | $displayname = ($tab.Displayname) -creplace '[^a-zA-Z0-9]', '' 79 | 80 | $switchstatement = @" 81 | {(`$$($displayname).checked)} {`$params += "'" + `$(`$tabs[$counter].FullPath) + "'"} 82 | "@ 83 | 84 | $counter++ 85 | 86 | [string]$switchstatements += "$switchstatement `n" 87 | } 88 | 89 | 90 | 91 | 92 | $events = @" 93 | #---------------------------------------------- 94 | #Generated Event Script Blocks 95 | #---------------------------------------------- 96 | #Provide Custom Code for events specified in PrimalForms. 97 | 98 | `$button1_OnClick= 99 | { 100 | 101 | `$numberofselectedcheckboxes = 0 102 | $ifstatements 103 | 104 | if (`$numberofselectedcheckboxes -le 1) 105 | { 106 | [System.Windows.Forms.MessageBox]::Show("No or only one Checkbox Selected!"); 107 | `$form1.close() 108 | } 109 | elseif (`$numberofselectedcheckboxes -gt 2) 110 | { 111 | [System.Windows.Forms.MessageBox]::Show("Only 2 checkboxes allowed!"); 112 | } 113 | 114 | else { 115 | 116 | `$params = @() 117 | Switch ($switchs) 118 | { 119 | $switchstatements 120 | } 121 | 122 | `$params = (`$params | select -Unique) -join " " 123 | #Open WinMerge 124 | Invoke-Expression "C:\Temp\WinMergePortable\WinMergePortable.exe `$params" 125 | 126 | } 127 | `$form1.close() 128 | 129 | } 130 | 131 | `$button2_OnClick= 132 | { 133 | #TODO: Place custom script here 134 | `$form1.close() 135 | } 136 | 137 | `$OnLoadForm_StateCorrection= 138 | {#Correct the initial state of the form to prevent the .Net maximized form issue 139 | `$form1.WindowState = `$InitialFormWindowState 140 | } 141 | 142 | `$System_Drawing_Size = New-Object System.Drawing.Size 143 | `$System_Drawing_Size.Height = $y+70 144 | `$System_Drawing_Size.Width = 259 145 | `$form1.ClientSize = `$System_Drawing_Size 146 | `$form1.DataBindings.DefaultDataSourceUpdateMode = 0 147 | `$form1.Name = "form1" 148 | `$form1.Text = "Open WinMerge" 149 | 150 | "@ 151 | 152 | 153 | #End Events 154 | 155 | 156 | 157 | ################################################################## 158 | 159 | $tabs = $PSISe.PowerShellTabs.Files 160 | $counter = 0 161 | $y = 40 162 | foreach ($tab in $tabs) 163 | { 164 | $displayname = ($tab.Displayname) -creplace '[^a-zA-Z0-9]', '' 165 | $counter++ 166 | $y = $y+31 167 | 168 | $checkboxtemplate = @" 169 | 170 | `$$($displayname).DataBindings.DefaultDataSourceUpdateMode = 0 171 | 172 | `$System_Drawing_Point = New-Object System.Drawing.Point 173 | `$System_Drawing_Point.X = 23 174 | `$System_Drawing_Point.Y = $y 175 | `$$($displayname).Location = `$System_Drawing_Point 176 | `$$($displayname).Name = "$($displayname)" 177 | `$System_Drawing_Size = New-Object System.Drawing.Size 178 | `$System_Drawing_Size.Height = 24 179 | `$System_Drawing_Size.Width = 104 180 | `$$($displayname).Size = `$System_Drawing_Size 181 | `$$($displayname).TabIndex = $counter 182 | `$$($displayname).Text = "Tab $counter" 183 | `$$($displayname).UseVisualStyleBackColor = `$True 184 | 185 | `$form1.Controls.Add(`$$($displayname)) 186 | "@ 187 | 188 | #Add each $checkboxtemplate to string 189 | [string]$checkboxtemplates += "$checkboxtemplate `n" 190 | } 191 | 192 | #final part 193 | $final = @" 194 | 195 | `$button2.DataBindings.DefaultDataSourceUpdateMode = 0 196 | 197 | `$System_Drawing_Point = New-Object System.Drawing.Point 198 | `$System_Drawing_Point.X = 150 199 | `$System_Drawing_Point.Y = $y+40 200 | `$button2.Location = `$System_Drawing_Point 201 | `$button2.Name = "button2" 202 | `$System_Drawing_Size = New-Object System.Drawing.Size 203 | `$System_Drawing_Size.Height = 23 204 | `$System_Drawing_Size.Width = 75 205 | `$button2.Size = `$System_Drawing_Size 206 | `$button2.TabIndex = 6 207 | `$button2.Text = "Cancel" 208 | `$button2.UseVisualStyleBackColor = `$True 209 | `$button2.add_Click(`$button2_OnClick) 210 | 211 | `$form1.Controls.Add(`$button2) 212 | 213 | 214 | `$button1.DataBindings.DefaultDataSourceUpdateMode = 0 215 | 216 | `$System_Drawing_Point = New-Object System.Drawing.Point 217 | `$System_Drawing_Point.X = 33 218 | `$System_Drawing_Point.Y = $y+40 219 | `$button1.Location = `$System_Drawing_Point 220 | `$button1.Name = "button1" 221 | `$System_Drawing_Size = New-Object System.Drawing.Size 222 | `$System_Drawing_Size.Height = 23 223 | `$System_Drawing_Size.Width = 75 224 | `$button1.Size = `$System_Drawing_Size 225 | `$button1.TabIndex = 5 226 | `$button1.Text = "OK" 227 | `$button1.UseVisualStyleBackColor = `$True 228 | `$button1.add_Click(`$button1_OnClick) 229 | 230 | `$form1.Controls.Add(`$button1) 231 | 232 | `$label1.DataBindings.DefaultDataSourceUpdateMode = 0 233 | 234 | `$System_Drawing_Point = New-Object System.Drawing.Point 235 | `$System_Drawing_Point.X = 23 236 | `$System_Drawing_Point.Y = 13 237 | `$label1.Location = `$System_Drawing_Point 238 | `$label1.Name = "label1" 239 | `$System_Drawing_Size = New-Object System.Drawing.Size 240 | `$System_Drawing_Size.Height = 23 241 | `$System_Drawing_Size.Width = 171 242 | `$label1.Size = `$System_Drawing_Size 243 | `$label1.TabIndex = 1 244 | `$label1.Text = "Select two open ISE tabs" 245 | 246 | `$form1.Controls.Add(`$label1) 247 | 248 | #endregion Generated Form Code 249 | 250 | #Save the initial state of the form 251 | `$InitialFormWindowState = `$form1.WindowState 252 | #Init the OnLoad event to correct the initial state of the form 253 | `$form1.add_Load($`OnLoadForm_StateCorrection) 254 | #Show the Form 255 | `$form1.ShowDialog()| Out-Null 256 | "@ 257 | 258 | #$final 259 | 260 | $code = @" 261 | $assemblies 262 | $objects 263 | $events 264 | $checkboxtemplates 265 | $final 266 | "@ 267 | 268 | Invoke-Expression $code -------------------------------------------------------------------------------- /Examples/DSC_CreateOM12ServiceAccounts.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\DSC_CreateOM12ServiceAccounts.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 12/02/2014 11:30:30 6 | # Description: Creates OM12 Service Accounts and adds them to the Domain Admins Groups. 7 | # Comments: Needs a ConfigurationData file. 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | configuration OM12DomainUsers 15 | { 16 | param 17 | ( 18 | [Parameter(Mandatory)] 19 | [pscredential]$domainCred 20 | 21 | ) 22 | 23 | Import-DscResource -ModuleName xActiveDirectory 24 | 25 | Node $AllNodes.Where{$_.Role -eq "Primary DC"}.Nodename 26 | { 27 | foreach ($User in $Node.Users) 28 | { 29 | xADUser $User.Username 30 | { 31 | Ensure = 'Present' UserName = $User.Username 32 | Password = $domainCred 33 | DomainName = $Node.DomainName 34 | DomainAdministratorCredential = $domainCred 35 | } 36 | } 37 | 38 | 39 | Script AddServiceAccounts { 40 | GetScript = { 41 | @{ 42 | GetScript = $GetScript 43 | SetScript = $SetScript 44 | TestScript = $TestScript 45 | $Users = $($using:Node.Users.UserName) 46 | $Group = $($using:Node.GroupName) 47 | Result = foreach ($User in $Users) { 48 | (Get-ADPrincipalGroupMembership -Identity $User).Name 49 | } 50 | 51 | } 52 | } 53 | 54 | SetScript = { 55 | $Users = $($using:Node.Users.UserName) 56 | $Group = $($using:Node.GroupName) 57 | foreach ($User in $Users) { 58 | Write-Verbose "$User is being iterated for $Group" 59 | $ADUser = Get-ADUser -Identity $User -ErrorAction SilentlyContinue; 60 | if ($ADUser) { 61 | Add-ADGroupMember -Identity $Group -Members $ADUser; 62 | } 63 | $ADUser = $null; 64 | } 65 | } 66 | 67 | TestScript = { 68 | $Users = $($using:Node.Users.UserName) 69 | $Group = $($using:Node.GroupName) 70 | foreach ($User in $Users) { 71 | Write-Verbose "$User is being checked for $Group" 72 | if (Get-ADPrincipalGroupMembership -Identity $User | where-object {$_.Name -eq $Group}) 73 | { 74 | $true 75 | Write-Verbose "User $user is member of Group $Group" 76 | } 77 | else 78 | { 79 | $false 80 | Write-Verbose "User $user is NOT member of Group $Group" 81 | return $false 82 | } 83 | } 84 | 85 | } 86 | }#End script 87 | 88 | 89 | #}#End foreach 90 | } 91 | 92 | } 93 | 94 | $cred = (Get-Credential -UserName Administrator -message "Enter Password") 95 | 96 | # Compile MOF 97 | OM12DomainUsers -domaincred $cred -ConfigurationData c:\scripts\4_CreateOM12ServiceAccountsConfigData.psd1 -OutputPath "$Env:Temp\OM12DomainUser" 98 | 99 | # Make it so! 100 | Start-DscConfiguration -Path "$Env:Temp\OM12DomainUser" -Wait -Verbose -Debug -Force -ErrorAction Continue 101 | -------------------------------------------------------------------------------- /Examples/DemoLogicalOperators.ps1: -------------------------------------------------------------------------------- 1 | # Demo Logical Operators 2 | # Comparison Operators are short circuit operators. 3 | # This means that if the expression on the left-hand side of the -end 4 | # operator is $false, the expression on the right-hand is not evaluated. 5 | 6 | #Compare the differences 7 | if ((5 -lt 4) -and (1..10000 | % {if ($_ -eq "never"){}})){} #takes not long because left-hand is false 8 | 9 | if ((3 -lt 4) -and (1..10000 | % {if ($_ -eq "never"){}})){} #takes some time to finish 10 | -------------------------------------------------------------------------------- /Examples/DscClassISESnippet.ps1: -------------------------------------------------------------------------------- 1 | New-IseSnippet -Title "DSC Class" -Author "Stefan Stranger" ` 2 | -Description "DSC Class Snippet" ` 3 | -Text (Get-Content .\DscClassIseSnippetCode.ps1 -Raw) -------------------------------------------------------------------------------- /Examples/DscClassISESnippetCode.ps1: -------------------------------------------------------------------------------- 1 | enum Ensure 2 | { 3 | Absent 4 | Present 5 | } 6 | 7 | [DscResource()] 8 | class ResourceName 9 | { 10 | [DscResourceKey()] 11 | #Some Key Property 12 | 13 | [DscResourceMandatory()] 14 | #Some Mandatory property 15 | 16 | #Use of enumeration 17 | [Ensure] $Ensure 18 | 19 | #Set function similar to Set-TargetResource 20 | [void] Set() 21 | { 22 | #Set logic goes here 23 | } 24 | 25 | #Test function similar to Test-TargetResource 26 | [bool] Test() 27 | { 28 | #Test logic goes here 29 | } 30 | 31 | #Get function similar to Get-TargetResource 32 | [Hashtable] Get() 33 | { 34 | #Get logic goes here 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Examples/ExportBitlocker.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 4 2 | #requires -runasadministrator 3 | 4 | # --------------------------------------------------- 5 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\ExportBitlocker.ps1 6 | # Version: 0.1 7 | # Author: Stefan Stranger 8 | # Date: 02/26/2014 14:18:50 9 | # Description: Function to export Bitlocker Keys for storing in files. 10 | # Comments: 11 | # --------------------------------------------------- 12 | 13 | <# 14 | .Synopsis 15 | Backup Bitlocker key and store on OneDrive 16 | .DESCRIPTION 17 | Script to backup bitlocker and store the bitlocker key on OneDrive 18 | .EXAMPLE 19 | Backup-BitlockerToOneDrive -DriveLetter C: 20 | Shows Bitlocker key for DriveLetter C: in PowerShell host. 21 | .EXAMPLE 22 | Backup-BitlockerToOneDrive -DriveLetter c: | export-csv -path c:\temp\bitlocker.csv -notypeinformation 23 | Exports Bitlocker key for Driveletter C: to bitlocker.csv file on c:\temp folder without any typeinformation 24 | .EXAMPLE 25 | "c:","d:" | Backup-BitlockerToOneDrive | export-csv -path c:\temp\bitlocker.csv -notypeinformation -Append 26 | Exports and appends the Bitlocker keys for Driveletter C: and D: using the pipeline to bitlocker.csv file on c:\temp folder without any typeinformation with verbose info 27 | .EXAMPLE 28 | #Function need to run elevated. Let's create an option 29 | $option = New-ScheduledJobOption -RunElevated 30 | 31 | #Register BackupBitlocker Job 32 | Register-ScheduledJob -name BackupBitlocker -ScriptBlock { 33 | . C:\Scripts\PS\Bitlocker\ExportBitlocker.ps1 34 | Backup-BitlockerToOneDrive -DriveLetter C: | export-csv -path C:\users\stefstr\SkyDrive\Bitlocker\backupbitlocker.csv -Append 35 | } -ScheduledJobOption $option 36 | 37 | #Create Trigger 38 | $4amtrigger = New-JobTrigger -At 4pm -Daily 39 | 40 | #Associate a Job Trigger 41 | Add-JobTrigger -Name BackupBitlocker -Trigger $4amtrigger 42 | #> 43 | function Backup-BitlockerToOneDrive 44 | { 45 | [CmdletBinding()] 46 | [OutputType([String])] 47 | Param 48 | ( 49 | # Param1 help description 50 | [Parameter(Mandatory=$true, 51 | ValueFromPipeline=$true, 52 | Position=0)] 53 | [string] 54 | $DriveLetter 55 | ) 56 | 57 | Begin 58 | { 59 | Write-Verbose "Starting Backup-BitLockerToOneDrive Function" 60 | 61 | } 62 | Process 63 | { 64 | Write-Verbose "Bitlocker PowerShell object is being created" 65 | $bitlockerobject = new-object -type psobject -Property @{Driveletter="";RecoveryPassWord="";BackupDate="";Computername=""} 66 | $bitlockerobject.ComputerName = $($env:COMPUTERNAME) 67 | $bitlockerobject.BackupDate = $(Get-Date) 68 | $bitlockerobject.Driveletter = $DriveLetter 69 | $bitlockerobject.RecoveryPassWord = [string]$((Get-BitLockerVolume -MountPoint $driveletter).KeyProtector.recoverypassword) 70 | $bitlockerobject 71 | } 72 | End 73 | { 74 | Write-Verbose "Finished Backup-BitLockerToOneDrive Function" 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Examples/FastSealWrapper.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Scripts\PS\FastSealWrapper.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 10/21/2015 19:12:12 (Backtothefuture) 6 | # Description: Wrapper function around FastSeal tool to Seal Operations Manager MP xml files 7 | # Comments: You need to use sn.exe to create a key file first 8 | # Check https://technet.microsoft.com/en-us/library/hh457550.aspx on how to create a keyfile 9 | # Use FastSeal.exe from Silects MP Author tool found in folder C:\Program Files\Silect\MP Author\MPSeal 10 | # Download MP Author from: http://www.silect.com/mp-author 11 | # If you have the fastseal.exe tool installed in another folder change the fastseal variable on line 57 of script. 12 | # Changes: 13 | # Disclaimer: 14 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 15 | # **Always test in your lab first** Do this at your own risk!! 16 | # The author will not be held responsible for any damage you incur when making these changes! 17 | # --------------------------------------------------- 18 | 19 | 20 | Function FastSeal-MP 21 | <# 22 | .Synopsis 23 | Function to Seal OpsMgr Management Packs 24 | .DESCRIPTION 25 | Wrapper Function around the FastSeal tool to easily seal Operations Manager Management Pack XML files. 26 | .EXAMPLE 27 | FastSeal-MP -MPFileName C:\temp\MPSeal\Fake.MP\Fake.MP.xml -KeyFileName C:\temp\MPSeal\pairkey.snk -OutDir C:\temp\mpseal\Output -CompanyName "Stranger" 28 | Seals the Fake.MP.xml with KeyFile pairkey.snk and stores the Fake.MP.mp files in C:\temp\mpseal\Output folder 29 | .EXAMPLE 30 | dir C:\temp\MPSeal\Input | FastSeal-MP -KeyFileName C:\temp\MPSeal\pairkey.snk -OutDir C:\temp\mpseal\Output -CompanyName "Stranger" 31 | Pipes the results from the MP xml files stored in the C:\temp\MPSeal\Input folder and seals the MPs. 32 | #> 33 | { 34 | [CmdletBinding()] 35 | [OutputType([string])] 36 | Param 37 | ( 38 | # Param1 help description 39 | [Parameter(Mandatory=$true, 40 | ValueFromPipelineByPropertyName=$true, 41 | Position=0)] 42 | [Alias("FullName")] 43 | [String[]] 44 | $MPFileName, 45 | # OutDir 46 | [string] 47 | $Outdir, 48 | # KeyFileName 49 | [string] 50 | $KeyFileName, 51 | # CompanyName 52 | [string] 53 | $CompanyName 54 | ) 55 | Begin 56 | { 57 | $FastSeal = "C:\Program Files\Silect\MP Author\MPSeal\FastSeal.exe" 58 | } 59 | process{ 60 | $command = "'$FastSeal' " + "$MPFileName /KeyFile $KeyFileName /CompanyName $companyName /OutDir $OutDir" 61 | $ErrorActionPreference = 'silentlycontinue' 62 | & $FastSeal $MPFileName /KeyFile $KeyFileName /OutDir $OutDir /Company $companyName 63 | $erroraction = 'continue' 64 | $error[0] 65 | } 66 | End 67 | { 68 | 69 | } 70 | } 71 | 72 | -------------------------------------------------------------------------------- /Examples/Find-Package-Project-Website.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\Find-Package-Project-Website.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 04/07/2014 21:45:57 6 | # Description: Helper Function to find Package Project Website for OneGet Find-Package Cmdlet 7 | # Comments: 8 | # Disclamer: This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment. 9 | # --------------------------------------------------- 10 | 11 | #Help function to open internet explorer 12 | Function Start-IE 13 | { 14 | [CmdletBinding()] 15 | [OutputType([string])] 16 | Param 17 | ( 18 | # Param1 help description 19 | [Parameter(Mandatory=$true, 20 | ValueFromPipeline=$true, 21 | ValueFromPipelineByPropertyName=$true, 22 | Position=0)] 23 | $url) 24 | 25 | Process 26 | { 27 | start $url 28 | } 29 | 30 | } 31 | 32 | 33 | 34 | Function Find-PackageSite 35 | { 36 | <# 37 | .Synopsis 38 | Find OneGet Package Site 39 | .DESCRIPTION 40 | Function to find the url for the Package Site from the OneGet Find-Package Cmdlet 41 | .EXAMPLE 42 | Find-PackageSite -Name Console2 -Source Chocolatey 43 | This command gets the Project website url for the Console2 package from Chocolatey resource 44 | PS C:\Scripts\PS> Find-PackageSite -Name Console2 -Source Chocolatey 45 | http://sourceforge.net/projects/console/ 46 | .EXAMPLE 47 | Find-PackageSite -Name Console2 -Source "https://www.nuget.org/api/v2/" 48 | This command gets the Project website url for the Console2 package from Nuget resource 49 | PS C:\Scripts\PS> Find-PackageSite -Name Console2 -Source "https://www.nuget.org/api/v2/" 50 | http://sourceforge.net/projects/console/ 51 | .EXAMPLE 52 | Find-Package -Name console2 -source chocolatey | Find-PackageSite 53 | The results from the OneGet Find-Package cmdlet with source parameter are send through the pipeline 54 | to the Find-PackageSite function. 55 | PS C:\Scripts\PS> Find-Package -Name console2 -source chocolatey | Find-PackageSite 56 | http://sourceforge.net/projects/console/ 57 | .EXAMPLE 58 | Find-Package -Name console2 | Find-PackageSite 59 | PS C:\Scripts\PS> Find-Package -Name console2 | Find-PackageSite 60 | http://sourceforge.net/projects/console/ 61 | http://sourceforge.net/projects/console/ 62 | .EXAMPLE 63 | Find-Package -Name console2 -Source Chocolatey | Find-PackageSite | Start-IE 64 | The result from the OneGet Find-Package Cmdlet with source parameter is send through the pipeline 65 | to the Find-PackageSite function which is piped to the Start-IE Function to open the URL in Internet Explorer. 66 | #> 67 | 68 | [CmdletBinding()] 69 | [OutputType([string])] 70 | Param 71 | ( 72 | # Name parameter 73 | [Parameter(Mandatory=$true, 74 | ValueFromPipeline=$true, 75 | ValueFromPipelineByPropertyName=$true, 76 | Position=0)] 77 | $name, 78 | # Name parameter 79 | [Parameter(Mandatory=$false, 80 | ValueFromPipeline=$true, 81 | ValueFromPipelineByPropertyName=$true)] 82 | $Source) 83 | 84 | Process 85 | { 86 | #check if parameter has name property. 87 | if ($name.name) 88 | { 89 | $name = $name.name 90 | } 91 | 92 | #check source 93 | if ($source.source) 94 | { 95 | $source = $source.source 96 | } 97 | 98 | Write-Verbose "Using source: $source" 99 | 100 | if ($source -eq "Chocolatey") 101 | { 102 | write-verbose "Calling http://chocolatey.org/packages/$($name)" 103 | ((invoke-webrequest "http://chocolatey.org/packages/$($name)").links | ? {$_.outertext -eq ' Project Site'}).href 104 | } 105 | if ($source -eq "https://www.nuget.org/api/v2/") 106 | { 107 | write-verbose "Calling http://www.nuget.org/packages/$($name)" 108 | ((invoke-webrequest "http://www.nuget.org/packages/$($name)").links | ? {$_.outertext -eq ' Project Site'}).href 109 | } 110 | if (!$source) 111 | { 112 | write-verbose "Calling http://chocolatey.org/packages/$($name)" 113 | ((invoke-webrequest "http://chocolatey.org/packages/$($name)").links | ? {$_.outertext -eq ' Project Site'}).href 114 | write-verbose "Calling http://www.nuget.org/packages/$($name)" 115 | ((invoke-webrequest "http://www.nuget.org/packages/$($name)").links | ? {$_.outertext -eq ' Project Site'}).href 116 | 117 | } 118 | 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /Examples/FunWithDynamicParams.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\FunWithDynamicParams.ps1 3 | # Version: 0.1. 4 | # Author: Stefan Stranger 5 | # Date: 04/01/2015 13:26:19 6 | # Description: Having fun with Dynamic Parameters 7 | # Comments: 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | Function Use-LessIntelliSense 15 | { 16 | [CmdletBinding()] 17 | Param() 18 | DynamicParam { 19 | $randomParam = (Get-Random -InputObject (65..90|ForEach-Object -Process { 20 | [char]$_ 21 | }) -Count 1) + 22 | [string]::Concat((Get-Random -InputObject (97..122|ForEach-Object -Process { 23 | [char]$_ 24 | }) -Count 8)) 25 | $attributes = New-Object -TypeName System.Management.Automation.ParameterAttribute 26 | $attributes.Mandatory = $true 27 | $attributes.HelpMessage = 'Random parameter name' 28 | $attributes.ParameterSetName = 'Random' 29 | $attributeCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute] 30 | $attributeCollection.Add($attributes) 31 | $random = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter -ArgumentList ($randomParam, [int], $attributeCollection) 32 | $paramDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary 33 | $paramDictionary.Add($randomParam, $random) 34 | return $paramDictionary 35 | } 36 | Begin { 37 | } 38 | Process { 39 | } 40 | End { 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Examples/Get-MPWiki-ConvertFromString.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 5.0 2 | 3 | # define a sample-driven template describing the data structure: 4 | $template = @' 5 | {name:Application Virtualization 4.5 (APP-V)} 6 | {version:4.5.0.0} 7 | {date:10/09/2008} 8 | {name:Application Virtualization Server 5.0 (APP-V)} 9 | {version:1.0} 10 | {date:04/12/2013} 11 | {name:BizTalk Server 2013 R2}
12 | {version:7.0.2008.0}
13 | {date:02/19/2015}
14 | {name:Dynamics AX 2009} 15 | {version:1.0.0.50} 16 | {date:06/16/2009} 17 | {name:Windows Server Storage Spaces 2012 R2} 18 | 19 |

{version:1.1.253.0}

20 | 21 |

{date:04/27/2015}

22 | {name:Windows Azure Pack (WAP) Update 1}
23 | {version:1.0.0.466}
24 | {date:09/16/2015}
25 | '@ 26 | 27 | #Load data from MP Wiki website 28 | $url = 'http://social.technet.microsoft.com/wiki/contents/articles/16174.microsoft-management-packs.aspx' 29 | $html = ((Invoke-WebRequest $url).AllElements| Where-Object {$_.tagname -eq 'tbody'}).innerhtml 30 | $html | ConvertFrom-String -TemplateContent $template -ErrorAction SilentlyContinue | 31 | select name,url,version, @{L='date';E={[datetime]$_.date}} | 32 | Out-GridView -Title 'Microsoft Management Packs Overview' -PassThru -------------------------------------------------------------------------------- /Examples/Get-MPWiki.ps1: -------------------------------------------------------------------------------- 1 | #requires -Version 2 2 | 3 | # --------------------------------------------------- 4 | # Script: C:\Scripts\PS\Get-MPWiki.ps1 5 | # Version: 0.1 6 | # Author: Stefan Stranger 7 | # Date: 10/08/2015 12:12:12 8 | # Description: Download MP info from MPWiki 9 | # http://social.technet.microsoft.com/wiki/contents/articles/16174.microsoft-management-packs.aspx 10 | # Comments: Initial version from Hans Zeitler (Microsoft) 11 | # Changes: 12 | # Disclaimer: 13 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 14 | # **Always test in your lab first** Do this at your own risk!! 15 | # The author will not be held responsible for any damage you incur when making these changes! 16 | # --------------------------------------------------- 17 | 18 | 19 | Function Get-MPWikiManagementPack 20 | { 21 | <# 22 | .Synopsis 23 | Download Management Pack info from Microsoft Management Packs Wiki 24 | .DESCRIPTION 25 | Download Management Pack info from Microsoft Management Packs Wiki 26 | http://social.technet.microsoft.com/wiki/contents/articles/16174.microsoft-management-packs.aspx 27 | .EXAMPLE 28 | Get-MPWikiManagementPack 29 | .EXAMPLE 30 | Get-MPWikiManagementPack | out-gridview 31 | #> 32 | [CmdletBinding()] 33 | [Alias()] 34 | [OutputType([string[]])] 35 | Param 36 | ( 37 | # MPWikiURL 38 | [Parameter(Mandatory = $false, 39 | ValueFromPipelineByPropertyName = $false, 40 | Position = 0)] 41 | $MPWikeURL = 'http://social.technet.microsoft.com/wiki/contents/articles/16174.microsoft-management-packs.aspx' 42 | ) 43 | 44 | Begin 45 | { 46 | #The HtmlAgilityPack.dll should be in the folder where you are calling the function from 47 | $Path = (get-location).Path 48 | Write-Verbose 'Check for Html Agility Pack' 49 | if(!(Test-Path -Path "$Path\HtmlAgilityPack.dll")) 50 | { 51 | Write-Host 'Required Assembly HtmlAgilityPack.dll Missing' -ForegroundColor Red 52 | Write-Host 'Please download the HtmlAgiliyPack from http://htmlagilitypack.codeplex.com' 53 | Write-Host "And copy the HtmlAgilityPack.dll for .NET $($PSVersionTable.CLRVersion.Major).$($PSVersionTable.CLRVersion.Minor)" 54 | break 55 | 56 | } 57 | 58 | Add-Type -Path "$Path\HtmlAgilityPack.dll" 59 | 60 | } 61 | Process 62 | { 63 | $doc = New-Object -TypeName HtmlAgilityPack.HtmlDocument 64 | 65 | # Create a WebClient Object for downloading the files with 66 | $WebClient = New-Object -TypeName System.Net.WebClient 67 | 68 | Write-Verbose "Downloading content from $MPWikeURL..." 69 | 70 | # Download the HTML and save it to File for processing via HTMLAgility 71 | $MPBlogHTML = $WebClient.DownloadString($MPWikeURL) 72 | 73 | # Load into HTMLAgility Document Object 74 | $doc.LoadHtml($MPBlogHTML) 75 | Write-Verbose 'Finished downloading.' 76 | 77 | # Find the Management Pack Table and Get the Rows 78 | $TableRows = $doc.DocumentNode.SelectNodes("//table[@class='sortable']//tr") 79 | 80 | # Skip Header 81 | $MPacks = $TableRows[1..($TableRows.Count-1)] 82 | 83 | # As the WebPage is EN-US make certain that the dates are converted Properly 84 | $CultureENUS = [CultureInfo]'en-US' 85 | $Global:ManagementPacks = foreach($node in $MPacks[0..($MPacks.count-2)]) 86 | { 87 | $Name = $node.SelectSingleNode('td[1]').InnerText 88 | $DLURL = $node.SelectSingleNode('td[1]/a').GetAttributeValue('href','') 89 | $Version = $node.SelectSingleNode('td[2]').InnerText 90 | $Date = $node.SelectSingleNode('td[3]').InnerText 91 | New-Object -TypeName PSObject -Property @{ 92 | Name = $Name 93 | Version = $Version 94 | Date = [DateTime]::Parse($Date,$CultureENUS) 95 | URL = $DLURL 96 | } 97 | } 98 | $ManagementPacks 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Examples/ISEAdOn_Example.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\ISEAdOn_Example.ps1 3 | # Version: 4 | # Author: Stefan Stranger 5 | # Date: 02/26/2014 12:48:19 6 | # Description: 7 | # Comments: Current file is currently not working. It's retrieving the value of the script that loads the add-on. 8 | # Fixes: Fixed issues with not updating Date and showing currect file location. 9 | # --------------------------------------------------- 10 | 11 | [void]$psise. 12 | CurrentPowerShellTab. 13 | AddOnsMenu. 14 | SubMenus. 15 | Add("Insert Standard Header", 16 | {C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\scriptheader.ps1;$PSISE.CurrentFile.Editor.InsertText($header)} , "ALT+H") 17 | -------------------------------------------------------------------------------- /Examples/ISESteroids_Context-Menu_BackTicks.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\ISESteroids_Context-Menu_BackTicks.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 03/06/2015 10:04:40 6 | # Description: Testing new SteroidsContext Menu cmdlet for Preview Version 2.0.15.4 7 | # Comments: 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | Add-SteroidsContextMenuCommand -DisplayName 'Check for backticks' -ToolTip 'Check for backticks' -TokenType String -ScriptBlock { 15 | $content = $psISE.CurrentFile.Editor.Text 16 | $count = ([regex]::matches($content, '`')).count 17 | [System.Windows.Forms.MessageBox]::Show("$count backticks found","ISESteroids",0,"Information"); 18 | 19 | } -------------------------------------------------------------------------------- /Examples/InstallBoot2DockerOnHyperV.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\InstallBoot2DockerOnHyperV.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 12/03/2014 10:51:25 6 | # Description: Powershell script to create a Boot2Docker VM on HyperV 7 | # Comments: First download the Boot2Docker.iso file from https://github.com/boot2docker/boot2docker/releases 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | 15 | #Variables 16 | $vmname = "Boot2Docker" 17 | $vhdpath = "D:\VMs\$vmname\Virtual Disks\boot2docker.vhdx" 18 | $VMPath = "D:\VMs" 19 | $VMSwitch = "Intel(R) Centrino(R) Advanced-N 6205 Virtual Switch" 20 | $Boot2DockerISO = "D:\ISOs\boot2docker.iso" 21 | 22 | New-item "D:\VMs\$vmname\Virtual Disks" -Type Directory 23 | 24 | 25 | New-VHD -Path $vhdpath –Dynamic –SizeBytes 2GB 26 | 27 | New-VM –Name $vmname –MemoryStartupBytes 1GB -NoVHD -Generation 1 28 | 29 | Add-VMHardDiskDrive $vmname -Path $vhdpath 30 | 31 | Add-VMNetworkAdapter -VMName $vmname -SwitchName $VMSwitch 32 | 33 | Set-VMDvdDrive -VMName $vmname -Path $Boot2DockerISO -ControllerNumber 1 -ControllerLocation 0 34 | 35 | Start-VM -Name $vmname 36 | -------------------------------------------------------------------------------- /Examples/InstallDSCResourceWave8.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\InstallDSCResourceWave8.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 12/01/2014 11:21:09 6 | # Description: Install DSC Resource Wave 8 using DSC 7 | # Comments: Idea from http://trevorsullivan.net/2014/08/21/use-powershell-dsc-to-install-dsc-resources/ 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | 15 | configuration DSCWave { 16 | Archive DSCWave { 17 | DependsOn = '[Script]DSCWave'; 18 | Ensure = 'Present'; 19 | Path = "$env:windir\temp\DSC Resource Kit Wave 8 11102014.zip"; 20 | Destination = "$env:ProgramFiles\WindowsPowerShell\Modules"; 21 | } 22 | 23 | Script DSCWave { 24 | GetScript = { @{ Result = (Test-Path -Path "$env:windir\temp\DSC Resource Kit Wave 8 11102014.zip"); } }; 25 | SetScript = { 26 | $Uri = 'https://gallery.technet.microsoft.com/DSC-Resource-Kit-All-c449312d/file/129525/1/DSC%20Resource%20Kit%20Wave%208%2011102014.zip'; 27 | $OutFile = "$env:windir\temp\DSC Resource Kit Wave 8 11102014.zip"; 28 | Invoke-WebRequest -Uri $Uri -OutFile $OutFile; 29 | Unblock-File -Path $OutFile; 30 | }; 31 | TestScript = { Test-Path -Path "$env:windir\temp\DSC Resource Kit Wave 8 11102014.zip"; } 32 | } 33 | 34 | File DSCWave { 35 | DependsOn = '[Script]DSCWave'; 36 | Ensure = 'Present'; 37 | DestinationPath = "$env:ProgramFiles\WindowsPowerShell\Modules"; 38 | SourcePath = "$env:ProgramFiles\WindowsPowerShell\Modules\All Resources"; 39 | Recurse = $true 40 | 41 | } 42 | 43 | Script RemoveDSCFolder { 44 | GetScript = { 45 | GetScript = $GetScript 46 | SetScript = $SetScript 47 | TestScript = $TestScript 48 | $SourcePath = "$env:ProgramFiles\WindowsPowerShell\Modules\All Resources" 49 | Result = Test-Path $SourcePath 50 | } 51 | 52 | SetScript = { 53 | $SourcePath = "$env:ProgramFiles\WindowsPowerShell\Modules\All Resources" 54 | Remove-Item $SourcePath -Recurse -Force 55 | } 56 | 57 | TestScript = { 58 | $SourcePath = "$env:ProgramFiles\WindowsPowerShell\Modules\All Resources" 59 | (!(Test-Path $SourcePath)) 60 | } 61 | } 62 | 63 | } 64 | 65 | 66 | # Compile MOF 67 | DSCWave -OutputPath "$Env:Temp\DSCWave" 68 | 69 | # Make it so! 70 | Start-DscConfiguration -Path "$Env:Temp\DSCWave" -Wait -Verbose -Force -ErrorAction Continue -------------------------------------------------------------------------------- /Examples/InstallMinecraftinContainer.ps1: -------------------------------------------------------------------------------- 1 | #Install MineCraft in Container 2 | #Steps from https://www.youtube.com/watch?v=J8Sw_xLPBE8 3 | #More info: http://www.shotgunventure.com/?p=132 4 | #Credits: Mitch Melton 5 | 6 | #Create new VMSwitch 7 | New-VMSwitch -Name DHCP -NetAdapterName Ethernet0 8 | #Create new container 9 | New-Container -Name MinecraftBase -ContainerImageName WindowsServerCore -switchName DHCP 10 | 11 | #Start Minecraft Container 12 | start-container -name MinecraftBase 13 | 14 | #Get ipaddress from Container 15 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {Get-NetIPAddress | select IPv4Address} 16 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {new-item c:\Minecraft -ItemType Directory} 17 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {Invoke-WebRequest 'http://javadl.sun.com/webapps/download/AutoDL?BundleId=107944' -outfile c:\Minecraft\javainstall.exe -useBasicParsing} 18 | $version = Invoke-WebRequest -Uri https://launchermeta.mojang.com/mc/game/version_manifest.json -UseBasicParsing | ConvertFrom-Json 19 | 20 | #Check latest version 21 | $version.latest 22 | 23 | #Use latest version info from version info 24 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {Invoke-WebRequest 'http://s3.amazonaws.com/Minecraft.Download/versions/1.9.2/minecraft_server.1.9.2.jar' -outfile c:\Minecraft\Minecraftserver.jar} 25 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {New-Item HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer} 26 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {New-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer -name DisableRollback -Type DWORD -value 1} 27 | 28 | #Install MineCraft 29 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {C:\Minecraft\javainstall.exe /s INSTALLDIR=c:\Java REBOOT=Disable} 30 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {Get-ChildItem c:\java} 31 | #Create Eula.txt 32 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {"By changing the setting below to TRUE you are identicating your agreement to our EULA (http://account.mojang.com/documents/minecraft_eula). `neula=true" | out-file -FilePath c:\minecraft\eula.txt -Encoding ascii} 33 | #Configure Minecraft server properties 34 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {"#MinecraftServerProperties`nmotd-Container SERVER!!!! `nonline-mode=false" | Out-File c:\minecraft\server.properties -Encoding ascii} 35 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {"banned-players.json","banned-ips.json","ops.json","whitelist.json" | ForEach-Object {New-Item -ItemType File c:\minecraft\$_}} 36 | #Start Minecraft Server 37 | Invoke-Command -ContainerName MinecraftBase -RunAsAdministrator {Set-location C:\minecraft; c:\java\bin\java.exe -jar Minecraftserver.jar nogui } 38 | 39 | 40 | -------------------------------------------------------------------------------- /Examples/MSBand_v0.1.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Scripts\PS\MSBand\MSBand_v0.1ps1.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 12/22/2014 19:12:12 6 | # Description: Connect to your Microsoft Band using PowerShell 7 | # Comments: Download the Microsoft Band Sync app for Windows Software from http://www.microsoft.com/en-us/download/details.aspx?id=44579 8 | # Idea from https://twitter.com/JustinAngel/status/529876592479047682/photo/1 via @justinangel 9 | # Changes: 10 | # Disclaimer: 11 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 12 | # **Always test in your lab first** Do this at your own risk!! 13 | # The author will not be held responsible for any damage you incur when making these changes! 14 | # --------------------------------------------------- 15 | 16 | <#Steps: 17 | 1. Connect to you MS Band using the Microsoft Band Sync app for Windows Software. 18 | 2. Quit Band Sync app for Windows Software 19 | 3. Run PowerShell commands 20 | #> 21 | 22 | #Load Microsoft Band Sync app for Windows Software assembly 23 | add-type -Path "C:\Program Files (x86)\Microsoft Band Sync\Microsoft.Cargo.Client.Desktop8.dll" 24 | 25 | 26 | #Get Connected Deviced 27 | $MSBands = [Microsoft.Cargo.Client.CargoClient]::GetConnectedDevicesAsync() 28 | 29 | #Initalize Cargo Client for MSBand 30 | $MSBandClient = [Microsoft.Cargo.Client.CargoClient]::CreateAsync($MSBands.Result[0]) 31 | $MSBandClient.Result 32 | 33 | #Get Members 34 | $MSBandClient.Result | Get-Member 35 | 36 | #Get Firmware Versions 37 | $MSBandClient.Result.FirmwareVersions 38 | 39 | #GetDeviceTheme 40 | $MSBandClient.Result.GetDeviceTheme() 41 | 42 | #Get TimeZone 43 | $MSBandClient.Result.GetDeviceTimeZone() 44 | 45 | #Get Last Run Statistics 46 | $MSBandClient.Result.GetLastRunStatistics() 47 | 48 | #Send Email Notification 49 | $MSBandClient.Result.SendEmailNotification("Testing","Sending a message from PowerShell",(Get-Date)) 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /Examples/ObjectConceptsExplained_v0.2.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | /'=----= ______ 3 | (( || "--.__." 4 | " @>||_____________// 5 | _______ /^\"""""""""""//\========) 6 | _--"""--/-. "\ // _\-:::-/_-. 7 | ." .-"""-/ "_\ "\ == // ;::\:::/::".\ 8 | ; / _/ " \\ "\-+//--..._\_/:::::\\ 9 | . ; o . || ( ()/)======(o)::::::. 10 | . \ ; .| -|.;____...."b:::::; 11 | . -._ _ - ; == :::::::::::; 12 | "-..____.' ls ":::::::' 13 | 14 | Credits: http://chris.com/ascii/index.php?art=transportation/bicycles 15 | 16 | Properties bicycle: 17 | NumberOfWheels 18 | Direction 19 | Status 20 | Brand 21 | 22 | Methods Bicycle 23 | Brake 24 | Cycle 25 | Steer 26 | #> 27 | 28 | 29 | $source = @" 30 | public class Bicycle 31 | { 32 | public Bicycle(string constructorBrand) //default constructor 33 | { 34 | 35 | brand = constructorBrand; 36 | } 37 | 38 | //properties 39 | private string status = "stopped"; 40 | private string direction = "straight"; 41 | private string brand; 42 | 43 | public static int NumberOfWheels = 2; 44 | 45 | //When Brake method is called Property Status is changed to "stopped" 46 | public string Brake () 47 | { 48 | return status = "stopped"; 49 | } 50 | 51 | //When Cycle method is called Property Status is changed to "running' 52 | public string Cycle () 53 | { 54 | return status = "running"; 55 | } 56 | 57 | // When Steer method is called the Property Direction is set. 58 | public string Steer(string a) 59 | { 60 | return direction = a; 61 | } 62 | 63 | 64 | // Status is a property which returns if the bicyle is stopped or running. 65 | public string Status 66 | { 67 | get 68 | { 69 | return this.status; 70 | } 71 | set 72 | { 73 | this.status = value; 74 | } 75 | } 76 | 77 | // Direction is a property which returns the direction of the bicylce ("straight","left", "right"). 78 | public string Direction 79 | { 80 | get 81 | { 82 | return this.direction; 83 | } 84 | set 85 | { 86 | this.direction = value; 87 | } 88 | } 89 | 90 | // Brand is a property which returns the brand of the bicylce. 91 | public string Brand 92 | { 93 | get 94 | { 95 | return this.brand; 96 | } 97 | set 98 | { 99 | this.brand = value; 100 | } 101 | } 102 | 103 | } 104 | "@ 105 | 106 | # Use Add-Type to compile the C# source code stored in $source here-string 107 | Add-Type -TypeDefinition $source 108 | 109 | 110 | # Class: defines characteristics of an object 111 | # For the Bicycle you can see it has some properties, like number of wheels, direction, status or brand and 112 | # methods (what you can do with it), like cycle, brake and steer. 113 | # So if it has two wheels, a direction, is running or stopped and a brand and you can steer etc. it's a bicycle. 114 | 115 | 116 | # Instance: an object is an instance of a particular class. 117 | # create a new instance of the class bicycle using a Constructor 118 | $MyBike = New-Object -TypeName Bicycle("Gazelle") 119 | 120 | 121 | # What are the members of the object we just created? 122 | $MyBike | Get-Member 123 | 124 | # If we want to find the static members of the object we just created we do the following. 125 | $MyBike | Get-Member -Static 126 | 127 | # Let's get cycling calling the Cycle method. 128 | $MyBike.Cycle() 129 | 130 | # We are approaching a stop sign let's hit the brakes 131 | $MyBike.Brake() 132 | 133 | # Finally let's continue with Cycle and turn left 134 | $MyBike.Cycle() 135 | $MyBike.Steer("left") 136 | 137 | # We can also create a collection (array) of bicycle objects. 138 | # Create an empty array 139 | $Bikes = @() 140 | 141 | # Add bicycle objects to the bikes array. 142 | $Bikes += $MyBike 143 | 144 | # Create a new instance of the class bicycle 145 | $YourBike = New-Object -TypeName Bicycle("Sparta") 146 | $Bikes += $YourBike 147 | 148 | -------------------------------------------------------------------------------- /Examples/Ping-IPRange.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\Ping-IPRange.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 03/05/2014 15:11:26 6 | # Description: Using PowerShell Workflows available in PowerShell v3 and above to ping a subnet range. 7 | # Comments: having fun with PowerShell Workflows :-) 8 | # --------------------------------------------------- 9 | 10 | Workflow Test-PingWF{ 11 | param([string[]]$iprange) 12 | 13 | foreach -parallel($ip in $iprange) 14 | { 15 | "Pinging: $ip" 16 | Test-Connection -ipaddres $ip -Count 2 -ErrorAction SilentlyContinue 17 | } 18 | } 19 | 20 | Test-PingWF -iprange (1..254 | % {"10.10.10."+$_}) -------------------------------------------------------------------------------- /Examples/ProblemStepRecorder.ps1: -------------------------------------------------------------------------------- 1 | #---------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\ProblemStepRecorder.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 07/08/2014 15:34:47 6 | # Description: Simple Wrapper for Problem Step Recorder 7 | # Comments: Initial idea, needs more options and features added. 8 | # Disclamer: This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment. 9 | # --------------------------------------------------- 10 | 11 | <#Problem Recorder Wrapper 12 | psr.exe [/start |/stop][/output ] [/sc (0|1)] [/maxsc ] 13 | [/sketch (0|1)] [/slides (0|1)] [/gui (o|1)] 14 | [/arcetl (0|1)] [/arcxml (0|1)] [/arcmht (0|1)] 15 | [/stopevent ] [/maxlogsize ] [/recordpid ] 16 | 17 | 18 | /start :Start Recording. (Outputpath flag SHOULD be specified) 19 | /stop :Stop Recording. 20 | /sc :Capture screenshots for recorded steps. 21 | /maxsc :Maximum number of recent screen captures. 22 | /maxlogsize :Maximum log file size (in MB) before wrapping occurs. 23 | /gui :Display control GUI. 24 | /arcetl :Include raw ETW file in archive output. 25 | /arcxml :Include MHT file in archive output. 26 | /recordpid :Record all actions associated with given PID. 27 | /sketch :Sketch UI if no screenshot was saved. 28 | /slides :Create slide show HTML pages. 29 | /output :Store output of record session in given path. 30 | /stopevent :Event to signal after output files are generated. 31 | 32 | PSR Usage Examples: 33 | 34 | psr.exe 35 | psr.exe /start /output fullfilepath.zip /sc1 /gui 0 /record 36 | /stopevent /arcetl 1 37 | 38 | psr.exe /start /output fullfilepath.xml /gui 0 /recordpid 39 | /stopevent 40 | 41 | psr.exe /start /output fullfilepath.xml /gui 0 /sc 1 /maxsc 42 | /maxlogsize /stopevent 43 | 44 | psr.exe /stop 45 | 46 | Notes: 47 | 1. Output path should include a directory path (e.g. '.\file.xml'). 48 | 2. Output file can either be a ZIP file or XML file 49 | 3. Can't specify /arcxml /arcetl /arcmht /sc etc. if output is not a ZIP f 50 | #> 51 | 52 | $psrCommand = "C:\Windows\System32\psr.exe" 53 | if (!(Test-Path $psrCommand)) { 54 | throw "psr.exe was not found at $psrCommand." 55 | } 56 | set-alias psr $psrCommand 57 | 58 | Function Start-PSR 59 | { 60 | param ( 61 | [string] $outputFile = $(throw "ZipFile must be specified.") 62 | ) 63 | 64 | psr /start /output $outputfile /gui 0 /sc 1 /sketch 1 /maxsc 100 65 | 66 | } 67 | 68 | 69 | Function Stop-PSR 70 | { 71 | psr /stop 72 | 73 | } -------------------------------------------------------------------------------- /Examples/RunbookAutomation.ps1: -------------------------------------------------------------------------------- 1 | #requires -Version 3 -Modules AzureRM.Automation, AzureRM.profile, AzureRM.Resources 2 | 3 | # --------------------------------------------------- 4 | # Script: C:\Users\stefstr\OneDrive - Microsoft\Scripts\PS\NN\RunbookAutomation.ps1 5 | # Version: 0.1 6 | # Author: Stefan Stranger 7 | # Date: 06/10/2016 13:01:29 8 | # Description: Script to test Runbooks 9 | # Comments: 10 | # Changes: 11 | # Disclaimer: 12 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 13 | # **Always test in your lab first** Do this at your own risk!! 14 | # The author will not be held responsible for any damage you incur when making these changes! 15 | # --------------------------------------------------- 16 | 17 | #Login to Azure 18 | Add-AzureRmAccount 19 | 20 | #Select Azure Subscription 21 | $subscriptionId = 22 | (Get-AzureRmSubscription | 23 | Out-GridView ` 24 | -Title 'Select an Azure Subscription ...' ` 25 | -PassThru).SubscriptionId 26 | 27 | Set-AzureRmContext -SubscriptionId $subscriptionId 28 | 29 | #Select ResourceGroup 30 | $ResourceGroup = Get-AzureRmResourceGroup | Out-GridView -PassThru 31 | 32 | 33 | #Select AutomationAccount 34 | $AutomationAccount = Get-AzureRmAutomationAccount -ResourceGroupName $ResourceGroup.ResourceGroupName | Out-GridView -PassThru 35 | 36 | #Retrieve Runbooks 37 | $runbook = Get-AzureRmAutomationRunbook -ResourceGroupName $ResourceGroup.ResourceGroupName -AutomationAccountName $AutomationAccount.AutomationAccountName | 38 | Out-GridView -Title 'Select Runbook' -PassThru 39 | 40 | 41 | #Show Runbook info 42 | $runbook 43 | 44 | 45 | #Enable Verbose logging 46 | $runbook | 47 | Set-AzureRmAutomationRunbook -LogVerbose $true 48 | 49 | 50 | #Start Runbook 51 | $runbook | 52 | Start-AzureRmAutomationRunbook -Wait 53 | 54 | 55 | #Check status Runbook 56 | $Result = (Get-AzureRMAutomationJob -ResourceGroupName $ResourceGroup.ResourceGroupName -AutomationAccountName $AutomationAccount.AutomationAccountName)[0] 57 | $Result 58 | 59 | #Get All Output 60 | Get-AzureRmAutomationJob -id $Result.JobId $ResourceGroup.ResourceGroupName -AutomationAccountName $AutomationAccount.AutomationAccountName | 61 | Get-AzureRmAutomationJobOutput | 62 | Select-Object -Property Summary, Type, Time 63 | 64 | #Disable Verbose Output 65 | $runbook | Set-AzureRmAutomationRunbook -LogVerbose $false 66 | -------------------------------------------------------------------------------- /Examples/ScriptExplorerGUI.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Scripts\PS\ScriptExplorerGUI.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 11/25/2014 09:43:27 6 | # Description: GUI for PowerShell scripts 7 | # Comments: 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | ISE -File ( 15 | Get-ChildItem -Path C:\Scripts\PS\*.ps1 -Recurse | 16 | Out-GridView -OutputMode Single -Title "Select PowerShell Script to Open:" | 17 | Select-Object -ExpandProperty FullName 18 | ) -------------------------------------------------------------------------------- /Examples/ScriptHeader.ps1: -------------------------------------------------------------------------------- 1 | $global:header = @" 2 | # --------------------------------------------------- 3 | # Script: $($psise.currentfile.fullpath) 4 | # Version: 5 | # Author: Stefan Stranger 6 | # Date: $(get-date) 7 | # Description: 8 | # Comments: 9 | # Changes: 10 | # Disclaimer: 11 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 12 | # **Always test in your lab first** Do this at your own risk!! 13 | # The author will not be held responsible for any damage you incur when making these changes! 14 | # --------------------------------------------------- 15 | "@ -------------------------------------------------------------------------------- /Examples/SuspendPowerPlan.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\SuspendPowerPlan.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 07/05/2014 15:01:57 6 | # Description: Helper Function to Suspend Power Plan when running PowerShell scripts 7 | # Comments: 8 | # Disclamer: This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment. 9 | # --------------------------------------------------- 10 | 11 | 12 | <# 13 | .Synopsis 14 | Function to suspend your currrent Power Plan settings when running a PowerShell script. 15 | .DESCRIPTION 16 | Function to suspend your currrent Power Plan settings when running a PowerShell script. 17 | Scenario: When downloading files using Robocopy from PowerShell you don't want your 18 | laptop to go into sleep mode. 19 | .EXAMPLE 20 | Suspend-PowerPlan -script c:\scripts\mylongrunningscript.ps1 21 | Run mylongrunningscript with sleep idle timeout prevented 22 | .EXAMPLE 23 | Suspend-Powerplan -script c:\scripts\mylongrunningscript.ps1 -option Display -Verbose 24 | Run mylongrunningscript with Display idle timeout prevented and verbose messages 25 | .LINK 26 | http://www.microsofttranslator.com/bv.aspx?from=ru&to=en&a=http%3A%2F%2Fsocial.technet.microsoft.com%2FForums%2Fen-US%2F1f4754cb-37bf-4e1d-a59f-ec0f1aaf9d1c%2Fsetthreadexecutionstate-powershell%3FThread%3A1f4754cb-37bf-4e1d-a59f-ec0f1aaf9d1c%3DMicrosoft.Forums.Data.Models.Discussion%26ThreadViewModel%3A1f4754cb-37bf-4e1d-a59f-ec0f1aaf9d1c%3DMicrosoft.Forums.CachedViewModels.ThreadPageViewModel%26forum%3Dscrlangru 27 | #> 28 | function Suspend-Powerplan 29 | { 30 | [CmdletBinding()] 31 | [Alias()] 32 | [OutputType([int])] 33 | Param 34 | ( 35 | # Param1 help description 36 | [Parameter(Mandatory=$true, 37 | Position=0)] 38 | $script, 39 | [ValidateSet("Away","Display","System")] 40 | [string]$option 41 | 42 | ) 43 | 44 | $code=@' 45 | [DllImport("kernel32.dll", CharSet = CharSet.Auto,SetLastError = true)] 46 | public static extern void SetThreadExecutionState(uint esFlags); 47 | '@ 48 | 49 | $ste = Add-Type -memberDefinition $code -name System -namespace Win32 -passThru 50 | $ES_CONTINUOUS = [uint32]"0x80000000" #Requests that the other EXECUTION_STATE flags set remain in effect until SetThreadExecutionState is called again with the ES_CONTINUOUS flag set and one of the other EXECUTION_STATE flags cleared. 51 | $ES_AWAYMODE_REQUIRED = [uint32]"0x00000040" #Requests Away Mode to be enabled. 52 | $ES_DISPLAY_REQUIRED = [uint32]"0x00000002" #Requests display availability (display idle timeout is prevented). 53 | $ES_SYSTEM_REQUIRED = [uint32]"0x00000001" #Requests system availability (sleep idle timeout is prevented). 54 | 55 | Switch ($option) 56 | { 57 | "Away" {$setting = $ES_AWAYMODE_REQUIRED} 58 | "Display" {$setting = $ES_DISPLAY_REQUIRED} 59 | "System" {$setting = $ES_SYSTEM_REQUIRED} 60 | Default {$setting = $ES_SYSTEM_REQUIRED} 61 | 62 | } 63 | 64 | Write-Verbose "Power Plan suspended with option: $option" 65 | 66 | $ste::SetThreadExecutionState($ES_CONTINUOUS -bor $setting) 67 | 68 | 69 | #do something 70 | Write-Verbose "Executing $script" 71 | 72 | &$script 73 | 74 | Write-Verbose "Power Plan suspension ended" 75 | $ste::SetThreadExecutionState($ES_CONTINUOUS) 76 | 77 | 78 | } 79 | 80 | -------------------------------------------------------------------------------- /Examples/Test-IEFavorite.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\Test-IEFavorite.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 05/18/2015 10:01:28 6 | # Description: Testing IE favorites with Test-Uri cmdlet 7 | # Comments: Retrieving IE favorite code from http://madprops.org/blog/List-Your-Favorites-in-PowerShell/ 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | 15 | gci $env:userprofile\favorites -rec -inc *.url | 16 | ? {select-string -inp $_ -quiet "^URL=http"} | 17 | select @{Name="Name"; Expression={[IO.Path]::GetFileNameWithoutExtension($_.FullName)}}, 18 | @{Name="URL"; Expression={get-content $_ | ? {$_ -match "^URL=http"} | % {$_.Substring(4)}}} | 19 | % {test-uri -Uri $_.URL} -------------------------------------------------------------------------------- /Examples/Test-PrimeNumber.ps1: -------------------------------------------------------------------------------- 1 | #requires -Version 2 2 | function Test-PrimeNumber 3 | { 4 | <# 5 | .Synopsis 6 | Checks if integer is a Prime Number 7 | .DESCRIPTION 8 | Checks if integer is a Prime Number. 9 | A Prime Number can be divided evenly only by 1 or itself. 10 | And it must be a whole number greater than 1. 11 | .EXAMPLE 12 | Test-PrimeNumber -Integer 7 13 | Returns the result of the integer 7 being a Prime Number 14 | .EXAMPLE 15 | 2..10 | Test-PrimeNumber -Verbose 16 | Shows for each of the range 2..10 if it is a prime number 17 | .EXAMPLE 18 | 2..100 | Test-PrimeNumber | select @{L='Result';E={$_}} | Group-Object -Property Result -NoElement 19 | Shows the number of Prime Numbers in the range 2 till 100. 20 | .PARAMETER Integer 21 | An integer for which the function checks if it is a Prime Number 22 | .LINK 23 | http://www.mathsisfun.com/prime_numbers.html 24 | 25 | #> 26 | [CmdletBinding()] 27 | [Alias()] 28 | [OutputType([boolean])] 29 | Param 30 | ( 31 | # Enter integer 32 | [Parameter(Mandatory = $true, 33 | ValueFromPipeline = $true, 34 | Position = 0)] 35 | [int] 36 | [ValidateScript({ 37 | $_ -ne 1 38 | })] #Checks if input integer is not 1 39 | $Integer 40 | ) 41 | 42 | Begin 43 | { 44 | Write-Verbose 'Test-PrimeNumber function started' 45 | 46 | } 47 | Process 48 | { 49 | 50 | $j = 2 51 | $flag = $false 52 | while ($j -le $Integer/2) 53 | { 54 | #Check if the modulus 2 (the remainder from a division operation) for the integer is 0 55 | #Example: Integer 3 (which is a Prime Number) 3 % 2 = 1 56 | if ($Integer % $j -eq 0) 57 | { 58 | $flag = $true 59 | break 60 | } 61 | else 62 | { 63 | $j++ 64 | } 65 | } 66 | 67 | if ($flag) 68 | { 69 | Write-Verbose "$Integer is not a prime number" 70 | return $false 71 | } 72 | else 73 | { 74 | Write-Verbose "$Integer is a prime number" 75 | return $true 76 | } 77 | } 78 | End 79 | { 80 | Write-Verbose 'Test-PrimeNumber function finished' 81 | Remove-Variable -Name j, integer 82 | } 83 | } -------------------------------------------------------------------------------- /Examples/ThankYou.ps1: -------------------------------------------------------------------------------- 1 | #Surprise Ascii image 2 | 3 | $base64 = @' 4 | JCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkDQokJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJCQkJCQkJCQkJCNPT0hISEVFIyQkJCQkJCQkJCQkJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCQkJCQkJCRISWl8aXxJaWlpaUlJK08kJCQkJCQkJCQkJCQkJCQkJCQkDQokJCQkJCQkJCQkJCQkTyt8fD18PT09Oz18aWlpfHxpSUUkJCQkJCQkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJCQjSGl8fHx8PTs9aT18PXx8SUlJSXx8aCMkJCQkJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCQkaElpfD09aT09aWlpfGlJK0lJaElJaT18RSQkJCQkJCQkJCQkJCQkDQokJCQkJCQkJCQkT2lpaWlpaXxpaUlJKysraGhISE9PaGh8fEgkJCQkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJGhpfGkrK2hoSStoaEhIT09PRUVFRUVIaUkrJCQkJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCRPaWloKytoSEhISE9FRSMjIyNFRUVFRWhJSSMkJCQkJCQkJCQkJCQkDQokJCQkJCQkJCQkTytoSEhIT09FRUVFIyMjIyMjRUVFRUVPaCtPJCQkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJE9oT09ISE9PRUVFRSMjIyMjIyMjRUVFT0hoTyQkJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCRIaE9PSEhPT0VFRSMjIyMjIyMjI0VFRUVPT08kJCQkJCQkJCQkJCQkDQokJCQkJCQkJCQkT0hFT0hISE9FRUVFIyMjIyMjIyMjRUVFT09PIyQkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJEVPRU9ISEhPRUVFRUVFIyMjIyMjRUVFRUhPT0VFJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCRISEVPSEhIT09FRSNFRSMjIyMjIyNFRUVPSE9FRSQkJCQkJCQkJCQkDQokJCQkJCQkJCQkI0hFT0hIT09PRUVFRUUjIyNFRUVFRU9FT09FRUUkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJCRPT09oKysraEhPT09PT0grSStIT09PRU9FT0UjJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCQkK0hPaCtpPT1pfElIRU8rK2lJSEhPRUVPRUVFIyQkJCQkJCQkJCQkDQokJCQkJCQkJCQkJEhPSGhoSCsrTys9TyNFT0hIT0VFRUVFT0VFIyMkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJCRFT09ISGhoSE9ISU9FRUVPT09FRUVFRU9FIyMkJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCQkI09ISE9PT09PK2hPRUVFRUVFRUVFRUVPRSMkJCQkJCQkJCQkJCQkDQokJCQkJCQkJCQkJCQjSE9PRUVFSGlIT0VFRUVPT0VFRUVFTyMkJCQkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJCQkJE9ISE9PT0krT08jRUVFRUVPSE9FSE8jJCQkJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCQkJCRPaGhoSGh8aU9PRUVPRUVFRUVIT09PIyQkJCQkJCQkJCQkJCQkDQokJCQkJCQkJCQkJCQkIytoaCtJSTs9K0hPRUVFT0hPRU9PTyQkJCQkJCQkJCQkJCQkJA0KJCQkJCQkJCQkJCQkJCRPaGgrfHxpaUlIT09PT0VFRU9PT0UkJCQkJCQkJCQkJCQkJCQNCiQkJCQkJCQkJCQkJCQkJEhoKytoSGhIT0VFRUVFRU9PT0hFRUUjJCMkJCQkJCQkJCQkDQokJCQkJCQkJCQkJCQkRWgrSEhoaGhoK2hIRUVFRUVPRU9PT0hpOzosO0lPJCQkJCQkJA0KJCQkJCQkJCQkRWhJOy4uPU9PSEhISE9PRUVFRUVFT09PRUVFRUVIaCs7O3wrTyQkJCQNCiQkJCQjSCt8OiwsLiAgLHxPSE9PT0hPT0VFRUVFT0hPRUVFRUVFRUVFPSwsLCw6SUUkDQpPaGk9OiwuLiwuLCAgLDo7SGhIT0hoaGhISEhIaEhPRUVFRUVFRUVFIz0sLCwsLCwsaQ0KOjosLC4uLi4sLi4gLDo6OkhIaEhISCtpaUkraEhPRUVFRUVFRUVFRSM7LCwsLCwsLCwNCiwsLi4uLi4uLi4uLDs7OjorSCsrSEhoK2hIT09FRUVFRUVFRUVFRSMjOiwsLCwsLCwsDQosLi4uLi4uLi4sLi49Ozs6fEhoKytIaCtoSE9PRUVFRU9FRUVFIyMjRTosLCwsLCwsLA0KLi4uLi4uLi4uLCwufHw9OzpJaGhoaGhoaEhPT0VPT09FRUVFRSMjI2g6OiwsLCwsLCwNCi4sLC4uLi4uLiwsLjpJPWk7O2kraGhoaEhIT09PT09PRUUjIyMjI2g6LCwsLCwsLCwsDQosLCwuLi4uLi4sLC4uPStpSXx8fCtoSEhISE9PT09FRUVFIyNFSHw6LCwsLCwsLCwsLA0KLCwsLC4sLi4uLiwsLi5JaCtoaEl8aEhPSEhIT0VFRUVFRUVoOywsLCwsLCwsLCwsLCwNCiwsLCwsLCwuLi4uLCwsLGhISEhIT09FT09FRUVFRUVFRWg7LCwsLiwsLCwsLCwsLCwsDQosLCwsLCwsLCwuLi4sLCw6SE9PT0VFT09FRUVFRUVFSD0sLi4uLiwsLCwsLCwsLCwsLA0KLi4uLCwuLCwsLCwuLiwsLDtPRUVFRUVFRUVFRUVPaSwuLi4uLi4uLC4uLi4uLCwsLCwNCi4uLi4uLi4uLCwuLC4uLCwsPUVFRUVFRUVFRUUrOi4uLi4uLi4uLi4uLi4uLiwsLCwsDQouLi4uLi4uLi4uLi4sLi4sLCw9T0VFRUVFRUg7Li4uLi4uLi4uLi4uLi4uLiwsLCwsLA0KLCwsLC4uLCwuLi4uLCwuLi4uLjpoRUVFT2ksLi4uLi4uLiAgIC4uLi4uLi4uLi4uLCwNCiwsLCwsLCwsLCwsLCwsLi4uLi4uLHxISSwuLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uDQojIyMjIyMjIFRoYW5rIHlvdSBmb3IgdGhlIGJpcnRoZGF5IHdpc2hlcyAjIyMjIyMjIw0KLCwsLCwsLCwsLCwsLCwsLCwuLi4uLiwuLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4= 5 | '@ 6 | 7 | [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($base64)) -------------------------------------------------------------------------------- /Examples/Top2000.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Top2000 lijst 4 | .DESCRIPTION 5 | Overzicht van de Top2000 6 | .EXAMPLE 7 | Get-Top2000 8 | Overzicht van de Top2000 van het jaar 2015 9 | .EXAMPLE 10 | Get-Top2000 -jaar 2014 11 | Overzicht van de Top2000 van het jaar 2014 12 | .URL 13 | http://www.nporadio2.nl/top2000 14 | #> 15 | function Get-Top2000 16 | { 17 | [CmdletBinding()] 18 | [Alias()] 19 | [OutputType([int])] 20 | Param 21 | ( 22 | # Param1 help description 23 | [Parameter(Mandatory=$false, 24 | Position=0)] 25 | [string] 26 | $jaar='2015' 27 | ) 28 | 29 | Begin 30 | { 31 | $urltop2000 = "http://www.nporadio2.nl/index.php?option=com_ajax&plugin=Top2000&format=json&year=$jaar" 32 | write-verbose "Retrieving $urltop2000" 33 | } 34 | Process 35 | { 36 | ((Invoke-RestMethod -Uri $urltop2000) | select-object -ExpandProperty data) | select-object @{L='Song';E={$_.s}}, @{L='Artiest';E={$_.a}}, @{L='Jaar';E={$_.yr}}, @{L='Positie';E={$_.pos}}, @{L='Verloop';E={$_.prv}} 37 | } 38 | End 39 | { 40 | write-verbose "Finished downloading top2000 from $jaar" 41 | } 42 | } -------------------------------------------------------------------------------- /Examples/WinMerge.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\WinMerge.ps1 3 | # Version: 0.2 4 | # Author: Stefan Stranger 5 | # Date: 02/09/2015 14:50:03 6 | # Description: WinMerge ISE AddOn. Opens first 2 open tabs in ISE 7 | # Comments: Download WinMergePortable from: http://sourceforge.net/projects/portableapps/files/WinMerge%20Portable/WinMergePortable_2.14.0.paf.exe 8 | # Install WinMergePortable and change below path to your WinMergePortable.exe folder. 9 | # Changes: 10 | # TODO: Currently the first 2 ISE tabs are automatically used in WinMerge. Future edition should have some more advanced options.[fixed] 11 | # Disclaimer: 12 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 13 | # **Always test in your lab first** Do this at your own risk!! 14 | # The author will not be held responsible for any damage you incur when making these changes! 15 | # --------------------------------------------------- 16 | 17 | [void]$psise. 18 | CurrentPowerShellTab. 19 | AddOnsMenu. 20 | SubMenus. 21 | Add("Open WINMERGE", 22 | {C:\Users\stefstr\Documents\GitHub\PowerShell\Examples\CreateWinForm_0.1.ps1} , "ALT+W") -------------------------------------------------------------------------------- /Examples/convert-image2text.ps1: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------ 2 | # Copyright 2006 Adrian Milliner (ps1 at soapyfrog dot com) 3 | # http://ps1.soapyfrog.com 4 | # 5 | # This work is licenced under the Creative Commons 6 | # Attribution-NonCommercial-ShareAlike 2.5 License. 7 | # To view a copy of this licence, visit 8 | # http://creativecommons.org/licenses/by-nc-sa/2.5/ 9 | # or send a letter to 10 | # Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. 11 | # Example: .\convert-image2text.ps1 -path "C:\Users\stefstr\Pictures\From HTC8x\Camera roll\WP_20140306_001.jpg" -maxwidth 50 12 | #------------------------------------------------------------------------------ 13 | 14 | # $Id: convert-image2text.ps1 91 2007-01-10 10:10:33Z adrian $ 15 | 16 | #------------------------------------------------------------------------------ 17 | # This script loads the specified image and outputs an ascii version to the 18 | # pipeline by line. 19 | # 20 | param( 21 | [string]$path = $(throw "Supply an image path"), 22 | [int]$maxwidth, # default is width of console 23 | [string]$palette="ascii", # choose a palette, "ascii" or "shade" 24 | [float]$ratio = 1.5 # 1.5 means char height is 1.5 x width 25 | ) 26 | 27 | 28 | 29 | #------------------------------------------------------------------------------ 30 | # here we go 31 | 32 | # the next line is require because FromFile below throws a /zero (?!) 33 | $path=(resolve-path -erroraction "stop" $path).path 34 | 35 | $palettes = @{ 36 | "ascii" = " .,:;=|iI+hHOE#`$" 37 | "shade" = " " + [char]0x2591 + [char]0x2592 + [char]0x2593 + [char]0x2588 38 | "bw" = " " + [char]0x2588 39 | } 40 | $c = $palettes[$palette] 41 | if (-not $c) { 42 | write-warning "palette should be one of: $($palettes.keys.GetEnumerator())" 43 | write-warning "defaulting to ascii" 44 | $c = $palettes.ascii 45 | } 46 | [char[]]$charpalette = $c.ToCharArray() 47 | 48 | # we need the drawing assembly 49 | <# 50 | $dllpath=(get-command "system.drawing.dll").definition 51 | [Reflection.Assembly]::LoadFrom($dllpath) | out-null 52 | #> 53 | Add-Type -AssemblyName System.Drawing 54 | # load the image 55 | $image = [System.Drawing.Image]::FromFile($path) 56 | if ($maxwidth -le 0) { [int]$maxwidth = $host.ui.rawui.WindowSize.Width - 1} 57 | [int]$imgwidth = $image.Width 58 | [int]$maxheight = $image.Height / ($imgwidth / $maxwidth) / $ratio 59 | $bitmap = new-object System.Drawing.Bitmap($image,$maxwidth,$maxheight) 60 | [int]$bwidth = $bitmap.Width; [int]$bheight = $bitmap.Height 61 | # draw it! 62 | $cplen = $charpalette.count 63 | for ([int]$y=0; $y -lt $bheight; $y++) { 64 | $line = "" 65 | for ([int]$x=0; $x -lt $bwidth; $x++) { 66 | $colour = $bitmap.GetPixel($x,$y) 67 | $bright = $colour.GetBrightness() 68 | [int]$offset = [Math]::Floor($bright*$cplen) 69 | $ch = $charpalette[$offset] 70 | if (-not $ch) { $ch = $charpalette[-1] } #overflow 71 | $line += $ch 72 | } 73 | $line 74 | } -------------------------------------------------------------------------------- /Examples/test.gitje: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanstranger/PowerShell/39abaa832c2108b716c506765d532188df8e3e55/Examples/test.gitje -------------------------------------------------------------------------------- /Get-TweetTimeline.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Goal: using Twitter API parameters like screen_name to retrieve tweets from a specific user. 3 | More info: https://dev.twitter.com/rest/reference/get/statuses/user_timeline 4 | Issue: Error "Could not authenticate you" when trying to add parameters to the HttpEndpoint. 5 | 6 | Remarks: 7 | Made a change to the Get-OAuthAuthorization function to be able to use the GET method instead of POST method. 8 | 9 | #> 10 | 11 | 12 | function Get-OAuthAuthorization { 13 | [CmdletBinding(DefaultParameterSetName = 'None')] 14 | [OutputType('System.Management.Automation.PSCustomObject')] 15 | param ( 16 | [Parameter(Mandatory)] 17 | [string]$HttpEndPoint, 18 | [Parameter(Mandatory, ParameterSetName = 'NewTweet')] 19 | [string]$TweetMessage, 20 | [Parameter(Mandatory, ParameterSetName = 'DM')] 21 | [string]$DmMessage, 22 | [Parameter(Mandatory, ParameterSetName = 'DM')] 23 | [string]$Username 24 | ) 25 | 26 | begin { 27 | $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop 28 | Set-StrictMode -Version Latest 29 | try { 30 | [Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null 31 | [Reflection.Assembly]::LoadWithPartialName("System.Net") | Out-Null 32 | } catch { 33 | Write-Error $_.Exception.Message 34 | } 35 | 36 | if(!(Test-Path -Path HKCU:\Software\MyTwitter)) 37 | { 38 | #Call Set-OAuthorization function 39 | Set-OAuthAuthorization 40 | } 41 | else 42 | { 43 | Write-Verbose "Retrieving Twitter Application settings from registry HKCU:\Software\MyTwitter" 44 | $global:APIKey = (Get-Item HKCU:\Software\MyTwitter).getvalue("APIKey") 45 | $global:APISecret = (Get-Item HKCU:\Software\MyTwitter).getvalue("APISecret") 46 | $global:AccessToken = (Get-Item HKCU:\Software\MyTwitter).getvalue("AccessToken") 47 | $global:AccessTokenSecret = (Get-Item HKCU:\Software\MyTwitter).getvalue("AccessTokenSecret") 48 | 49 | } 50 | } 51 | 52 | process { 53 | try { 54 | ## Generate a random 32-byte string. I'm using the current time (in seconds) and appending 5 chars to the end to get to 32 bytes 55 | ## Base64 allows for an '=' but Twitter does not. If this is found, replace it with some alphanumeric character 56 | $OauthNonce = [System.Convert]::ToBase64String(([System.Text.Encoding]::ASCII.GetBytes("$([System.DateTime]::Now.Ticks.ToString())12345"))).Replace('=', 'g') 57 | Write-Verbose "Generated Oauth none string '$OauthNonce'" 58 | 59 | ## Find the total seconds since 1/1/1970 (epoch time) 60 | $EpochTimeNow = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null) 61 | Write-Verbose "Generated epoch time '$EpochTimeNow'" 62 | $OauthTimestamp = [System.Convert]::ToInt64($EpochTimeNow.TotalSeconds).ToString(); 63 | Write-Verbose "Generated Oauth timestamp '$OauthTimestamp'" 64 | 65 | ## Build the signature 66 | $SignatureBase = "$([System.Uri]::EscapeDataString($HttpEndPoint))&" 67 | $SignatureParams = @{ 68 | 'oauth_consumer_key' = $ApiKey; 69 | 'oauth_nonce' = $OauthNonce; 70 | 'oauth_signature_method' = 'HMAC-SHA1'; 71 | 'oauth_timestamp' = $OauthTimestamp; 72 | 'oauth_token' = $AccessToken; 73 | 'oauth_version' = '1.0'; 74 | } 75 | if ($TweetMessage) { 76 | $SignatureParams.status = $TweetMessage 77 | } elseif ($DmMessage) { 78 | $SignatureParams.screen_name = $Username 79 | $SignatureParams.text = $DmMessage 80 | } 81 | 82 | 83 | ## Create a string called $SignatureBase that joins all URL encoded 'Key=Value' elements with a & 84 | ## Remove the URL encoded & at the end and prepend the necessary 'POST&' verb to the front 85 | $SignatureParams.GetEnumerator() | sort name | foreach { $SignatureBase += [System.Uri]::EscapeDataString("$($_.Key)=$($_.Value)&") } 86 | $SignatureBase = $SignatureBase.TrimEnd('%26') 87 | $SignatureBase = 'GET&' + $SignatureBase 88 | #$SignatureBase = 'POST&' + $SignatureBase 89 | Write-Verbose "Base signature generated '$SignatureBase'" 90 | 91 | ## Create the hashed string from the base signature 92 | $SignatureKey = [System.Uri]::EscapeDataString($ApiSecret) + "&" + [System.Uri]::EscapeDataString($AccessTokenSecret); 93 | 94 | $hmacsha1 = new-object System.Security.Cryptography.HMACSHA1; 95 | $hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($SignatureKey); 96 | $OauthSignature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($SignatureBase))); 97 | Write-Verbose "Using signature '$OauthSignature'" 98 | 99 | ## Build the authorization headers using most of the signature headers elements. This is joining all of the 'Key=Value' elements again 100 | ## and only URL encoding the Values this time while including non-URL encoded double quotes around each value 101 | $AuthorizationParams = $SignatureParams 102 | $AuthorizationParams.Add('oauth_signature', $OauthSignature) 103 | 104 | ## Remove any API call-specific params from the authorization params 105 | $AuthorizationParams.Remove('status') 106 | $AuthorizationParams.Remove('text') 107 | $AuthorizationParams.Remove('screen_name') 108 | 109 | $AuthorizationString = 'OAuth ' 110 | $AuthorizationParams.GetEnumerator() | sort name | foreach { $AuthorizationString += $_.Key + '="' + [System.Uri]::EscapeDataString($_.Value) + '", ' } 111 | $AuthorizationString = $AuthorizationString.TrimEnd(', ') 112 | Write-Verbose "Using authorization string '$AuthorizationString'" 113 | 114 | $AuthorizationString 115 | 116 | } catch { 117 | Write-Error $_.Exception.Message 118 | } 119 | } 120 | } 121 | 122 | 123 | Function Get-TweetTimeline 124 | { 125 | 126 | [CmdletBinding()] 127 | [OutputType('System.Management.Automation.PSCustomObject')] 128 | param ( 129 | [string[]]$User 130 | ) 131 | 132 | process 133 | { 134 | $HttpEndPoint = 'https://api.twitter.com/1.1/statuses/user_timeline.json' #working 135 | $HttpEndPoint = "http://api.twitter.com/1.1/statuses/user_timeline.json?include_entities=true&include_rts=true&exclude_replies=true&count=20&screen_name=$user" #notworking 136 | Write-Verbose $HttpEndPoint 137 | $AuthorizationString = Get-OAuthAuthorization -HttpEndPoint $HttpEndPoint -Verbose 138 | $Timeline = Invoke-RestMethod -URI $HttpEndPoint -Method Get -Headers @{ 'Authorization' = $AuthorizationString } -ContentType "application/x-www-form-urlencoded" 139 | $Timeline | Select Id, created_at, text, retweet_count, favorite_count 140 | } 141 | 142 | 143 | 144 | } 145 | 146 | Get-TweetTimeLine -User 'twitterapi' -Verbose -------------------------------------------------------------------------------- /Get-WebCamp.ps1: -------------------------------------------------------------------------------- 1 | function Get-WebCamImage { 2 | 3 | #requires -version 2.0 4 | 5 | <# 6 | .Synopsis 7 | Use PowerShell to preview video from your webcam and also take snapshots 8 | .Description 9 | This PowerShell script previews video from your webcam and takes snapshots to JPEG 10 | Script uses WebCamLib which is a C# wrapper around a couple of API's in avicap32.dll 11 | The script can run interactively or from the command line. 12 | You can use some other program like the old vidcap32.exe from MSFT to change the 13 | resolution of the captured image, i.e increase it to 640x480 14 | Video Preview must be partially visible or the photos will be frozen on last scene. 15 | Start the shell using a single-threaded apartment, Use -sta switch as per example 16 | Code uses clipboard to transfer photo which only works when powershell is in sta mode 17 | .Parameter AppActivate 18 | Application is forced on top to ensure picture is taken 19 | .Parameter CamIndex 20 | The camera is selected, use index 0 for the first camera 21 | .Parameter Interval 22 | When this parameter is used, a snapshot is taken every x second(s) 23 | .Parameter PathBase 24 | The base path that images are created. 25 | Defaults to "c:\cap\image" (ensure base 'folder' exists) 26 | Images are created - "c:\cap\image0.jpg","c:\cap\image1.jpg","c:\cap\image2.jpg" 27 | .Parameter UseCam 28 | start using camera straight away when this switch is selected 29 | 30 | .example 31 | Get-WebCamImage 32 | 33 | Description 34 | ----------- 35 | The camera application is displayed 36 | .example 37 | Get-WebCamImage -CamIndex 0 -UseCam 38 | 39 | Description 40 | ----------- 41 | The camera application is displayed, first camera in drop downlist is selected 42 | and started. 43 | .example 44 | Get-WebCamImage -CamIndex 0 -UseCam -interval 3 45 | 46 | Description 47 | ----------- 48 | The camera application is displayed, first camera in drop downlist is selected 49 | and started. A image is captured and saved in default path every 3 seconds 50 | .example 51 | %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -sta -WindowStyle Hidden -file C:\scripts\get-WebCam.ps1 52 | or 53 | powershell.exe C:\scripts\get-WebCam.ps1 -sta 54 | 55 | Description 56 | ----------- 57 | If you want to launch the application from a shortcut use this command or similar 58 | Note the -sta parameter is required. 59 | .Link 60 | http://social.technet.microsoft.com/Profile/en-US/?user=Matthew Painter 61 | .link 62 | http://weblogs.asp.net/nleghari/pages/webcam.aspx 63 | .Notes 64 | NAME: Get-WebCamImage 65 | VERSION: 1.0 66 | AUTHOR: Matthew Painter 67 | LASTEDIT: 26/09/2010 68 | 69 | #> 70 | [CmdletBinding()] 71 | 72 | Param ( 73 | [Parameter( 74 | ValueFromPipeline=$False, 75 | Mandatory=$False, 76 | HelpMessage="Application is forced on top to ensure picture is taken")] 77 | [Switch]$AppActivate, 78 | 79 | [Parameter( 80 | ValueFromPipeline=$False, 81 | Mandatory=$false, 82 | HelpMessage="The dropdown list index specifying the camera to be selected")] 83 | [int]$CamIndex=0, 84 | 85 | [Parameter( 86 | ValueFromPipeline=$False, 87 | Mandatory=$False, 88 | HelpMessage="Interval in seconds between each snapshot image taken")] 89 | [int]$Interval, 90 | 91 | [Parameter( 92 | ValueFromPipeline=$False, 93 | Mandatory=$False, 94 | HelpMessage="The base path that images are created")] 95 | [String]$PathBase="c:\cap\image", 96 | 97 | [Parameter( 98 | ValueFromPipeline=$False, 99 | Mandatory=$false, 100 | HelpMessage="This parameter is a switch - start using camera straight away")] 101 | [switch]$UseCam 102 | ) 103 | 104 | $source=@" 105 | using System; 106 | using System.Collections.Generic; 107 | using System.Text; 108 | using System.Collections; 109 | using System.Runtime.InteropServices; 110 | using System.ComponentModel; 111 | using System.Data; 112 | using System.Drawing; 113 | using System.Windows.Forms; 114 | 115 | namespace WebCamLib 116 | { 117 | public class Device 118 | { 119 | private const short WM_CAP = 0x400; 120 | private const int WM_CAP_DRIVER_CONNECT = 0x40a; 121 | private const int WM_CAP_DRIVER_DISCONNECT = 0x40b; 122 | private const int WM_CAP_EDIT_COPY = 0x41e; 123 | private const int WM_CAP_SET_PREVIEW = 0x432; 124 | private const int WM_CAP_SET_OVERLAY = 0x433; 125 | private const int WM_CAP_SET_PREVIEWRATE = 0x434; 126 | private const int WM_CAP_SET_SCALE = 0x435; 127 | private const int WS_CHILD = 0x40000000; 128 | private const int WS_VISIBLE = 0x10000000; 129 | 130 | [DllImport("avicap32.dll")] 131 | protected static extern int capCreateCaptureWindowA([MarshalAs(UnmanagedType.VBByRefStr)] ref string lpszWindowName, 132 | int dwStyle, int x, int y, int nWidth, int nHeight, int hWndParent, int nID); 133 | 134 | [DllImport("user32", EntryPoint = "SendMessageA")] 135 | protected static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)] object lParam); 136 | 137 | [DllImport("user32")] 138 | protected static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags); 139 | 140 | [DllImport("user32")] 141 | protected static extern bool DestroyWindow(int hwnd); 142 | 143 | int index; 144 | int deviceHandle; 145 | 146 | public Device(int index) 147 | { 148 | this.index = index; 149 | } 150 | 151 | private string _name; 152 | 153 | public string Name 154 | { 155 | get { return _name; } 156 | set { _name = value; } 157 | } 158 | 159 | private string _version; 160 | 161 | public string Version 162 | { 163 | get { return _version; } 164 | set { _version = value; } 165 | } 166 | 167 | public override string ToString() 168 | { 169 | return this.Name; 170 | } 171 | 172 | public void Init(int windowHeight, int windowWidth, int handle) 173 | { 174 | string deviceIndex = Convert.ToString(this.index); 175 | deviceHandle = capCreateCaptureWindowA(ref deviceIndex, WS_VISIBLE | WS_CHILD, 0, 0, windowWidth, windowHeight, handle, 0); 176 | 177 | if (SendMessage(deviceHandle, WM_CAP_DRIVER_CONNECT, this.index, 0) > 0) 178 | { 179 | SendMessage(deviceHandle, WM_CAP_SET_SCALE, -1, 0); 180 | SendMessage(deviceHandle, WM_CAP_SET_PREVIEWRATE, 0x42, 0); 181 | SendMessage(deviceHandle, WM_CAP_SET_PREVIEW, -1, 0); 182 | SetWindowPos(deviceHandle, 1, 0, 0, windowWidth, windowHeight, 6); 183 | } 184 | } 185 | 186 | public void ShowWindow(global::System.Windows.Forms.Control windowsControl) 187 | { 188 | Init(windowsControl.Height, windowsControl.Width, windowsControl.Handle.ToInt32()); 189 | } 190 | 191 | public void CopyC() 192 | { 193 | SendMessage(this.deviceHandle, WM_CAP_EDIT_COPY, 0, 0); 194 | } 195 | 196 | public void Stop() 197 | { 198 | SendMessage(deviceHandle, WM_CAP_DRIVER_DISCONNECT, this.index, 0); 199 | DestroyWindow(deviceHandle); 200 | } 201 | } 202 | 203 | public class DeviceManager 204 | { 205 | [DllImport("avicap32.dll")] 206 | protected static extern bool capGetDriverDescriptionA(short wDriverIndex, 207 | [MarshalAs(UnmanagedType.VBByRefStr)]ref String lpszName, 208 | int cbName, [MarshalAs(UnmanagedType.VBByRefStr)] ref String lpszVer, int cbVer); 209 | 210 | static ArrayList devices = new ArrayList(); 211 | 212 | public static Device[] GetAllDevices() 213 | { 214 | String dName = "".PadRight(100); 215 | String dVersion = "".PadRight(100); 216 | 217 | for (short i = 0; i < 10; i++) 218 | { 219 | if (capGetDriverDescriptionA(i, ref dName, 100, ref dVersion, 100)) 220 | { 221 | Device d = new Device(i); 222 | d.Name = dName.Trim(); 223 | d.Version = dVersion.Trim(); 224 | devices.Add(d); 225 | } 226 | } 227 | 228 | return (Device[])devices.ToArray(typeof(Device)); 229 | } 230 | 231 | public static Device GetDevice(int deviceIndex) 232 | { 233 | return (Device)devices[deviceIndex]; 234 | } 235 | } 236 | } 237 | "@ 238 | 239 | Add-Type -AssemblyName System.Drawing 240 | $jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | 241 | Where-Object { $_.FormatDescription -eq "JPEG" } 242 | 243 | Add-Type -TypeDefinition $source -ReferencedAssemblies System.Windows.Forms, System.Data, System.Drawing 244 | 245 | 246 | 247 | #region Import the Assemblies 248 | [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null 249 | [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null 250 | #endregion 251 | 252 | #region Generated Form Objects 253 | $MainForm = New-Object System.Windows.Forms.Form 254 | $btnQuitApp = New-Object System.Windows.Forms.Button 255 | $btnCopyImage = New-Object System.Windows.Forms.Button 256 | $btnStopCam = New-Object System.Windows.Forms.Button 257 | $btnSelectDevice = New-Object System.Windows.Forms.Button 258 | $cmbDevices = New-Object System.Windows.Forms.ComboBox 259 | $picCapture = New-Object System.Windows.Forms.PictureBox 260 | $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState 261 | #endregion Generated Form Objects 262 | 263 | #Build drop down list 264 | $devices = [WebCamLib.DeviceManager]::GetAllDevices() 265 | foreach ($d in $devices) 266 | { 267 | $cmbDevices.Items.Add($d) | Out-Null 268 | } 269 | 270 | if ($devices.Length -gt 0) 271 | { 272 | $cmbDevices.SelectedIndex = 0 273 | } 274 | 275 | #Select Button code 276 | $handler_btnSelectDevice_Click= 277 | { 278 | $d = [WebCamLib.DeviceManager]::GetDevice($cmbDevices.SelectedIndex) 279 | $d.ShowWindow($picCapture) 280 | } 281 | 282 | #Copy Button Code 283 | $handler_btnCopyImage_Click= 284 | { 285 | [windows.forms.clipboard]::clear() 286 | $d.CopyC() 287 | $bitmap = [Windows.Forms.Clipboard]::GetImage() 288 | 289 | if ($bitmap -ne $null) 290 | { 291 | $ep = New-Object Drawing.Imaging.EncoderParameters 292 | $ep.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, [long]100) 293 | $c = 0 294 | while (Test-Path "${PathBase}${c}.jpg") 295 | { 296 | $c++ 297 | } 298 | $bitmap.Save("$PathBase$c.jpg", $jpegCodec, $ep) 299 | Write-host "Snap taken "$PathBase$c.jpg"" 300 | $bitmap.dispose() 301 | $ep.dispose() 302 | [windows.forms.clipboard]::clear() 303 | } 304 | else 305 | { 306 | write-host "no image on clipboard" 307 | } 308 | 309 | 310 | } 311 | 312 | #Stop Button Code 313 | $handler_btnStopCam_Click= 314 | { 315 | $d = [WebCamLib.DeviceManager]::GetDevice($cmbDevices.SelectedIndex) 316 | $d.Stop() 317 | if ($timer -ne $null){$timer.Stop()} 318 | } 319 | 320 | #Quit Button Code 321 | $handler_btnQuitApp_Click= 322 | { 323 | $MainForm.close() 324 | } 325 | 326 | 327 | $OnLoadForm_StateCorrection= 328 | {#Correct the initial state of the form to prevent the .Net maximized form issue 329 | $MainForm.WindowState = $InitialFormWindowState 330 | 331 | if($UseCam) 332 | { 333 | write-host "Using camera $CamIndex" 334 | $d = [WebCamLib.DeviceManager]::GetDevice($cmbDevices.$CamIndex) 335 | $d.ShowWindow($picCapture) 336 | } 337 | } 338 | 339 | if ($interval -gt 0) 340 | { 341 | # Make Timer 342 | [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") 343 | $timer = New-Object System.Windows.Forms.Timer 344 | if ($interval -gt 30 ) {$timer.Interval = 5000} Else {$timer.Interval = 1000} 345 | $SecsToInterval = $interval 346 | 347 | $timer.add_Tick({ 348 | 349 | $SecsToInterval -= ($timer.Interval / 1000) 350 | 351 | if ( $SecsToInterval -eq 0 ) 352 | { 353 | $SecsToInterval = $interval 354 | 355 | if ($Appactivate) 356 | { 357 | [void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic") 358 | [Microsoft.VisualBasic.Interaction]::AppActivate("PowerShell WebCam") 359 | } 360 | 361 | & $handler_btnCopyImage_Click 362 | } 363 | 364 | write-host " [ Next Snap in : $(new-Timespan -sec $SecsToInterval) ]" 365 | 366 | }) 367 | 368 | $timer.Enabled = $true 369 | $timer.Start() 370 | } 371 | 372 | 373 | #---------------------------------------------- 374 | #region Generated Form Code 375 | $MainForm.Text = "PowerShell WebCam" 376 | $MainForm.Name = "MainForm" 377 | $MainForm.DataBindings.DefaultDataSourceUpdateMode = 0 378 | $System_Drawing_Size = New-Object System.Drawing.Size 379 | #$System_Drawing_Size.Width = 271 380 | #$System_Drawing_Size.Height = 172 381 | $System_Drawing_Size.Width = 371 382 | $System_Drawing_Size.Height = 272 383 | $MainForm.ClientSize = $System_Drawing_Size 384 | 385 | $btnQuitApp.TabIndex = 5 386 | $btnQuitApp.Name = "btnQuitApp" 387 | $System_Drawing_Size = New-Object System.Drawing.Size 388 | $System_Drawing_Size.Width = 75 389 | $System_Drawing_Size.Height = 23 390 | $btnQuitApp.Size = $System_Drawing_Size 391 | $btnQuitApp.UseVisualStyleBackColor = $True 392 | 393 | $btnQuitApp.Text = "Quit" 394 | 395 | $System_Drawing_Point = New-Object System.Drawing.Point 396 | $System_Drawing_Point.X = 12 397 | $System_Drawing_Point.Y = 137 398 | $btnQuitApp.Location = $System_Drawing_Point 399 | $btnQuitApp.DataBindings.DefaultDataSourceUpdateMode = 0 400 | $btnQuitApp.add_Click($handler_btnQuitApp_Click) 401 | 402 | $MainForm.Controls.Add($btnQuitApp) 403 | 404 | $btnCopyImage.TabIndex = 4 405 | $btnCopyImage.Name = "btnCopyImage" 406 | $System_Drawing_Size = New-Object System.Drawing.Size 407 | $System_Drawing_Size.Width = 75 408 | $System_Drawing_Size.Height = 23 409 | $btnCopyImage.Size = $System_Drawing_Size 410 | $btnCopyImage.UseVisualStyleBackColor = $True 411 | 412 | $btnCopyImage.Text = "Copy" 413 | 414 | $System_Drawing_Point = New-Object System.Drawing.Point 415 | $System_Drawing_Point.X = 12 416 | $System_Drawing_Point.Y = 71 417 | $btnCopyImage.Location = $System_Drawing_Point 418 | $btnCopyImage.DataBindings.DefaultDataSourceUpdateMode = 0 419 | $btnCopyImage.add_Click($handler_btnCopyImage_Click) 420 | 421 | $MainForm.Controls.Add($btnCopyImage) 422 | 423 | $btnStopCam.TabIndex = 3 424 | $btnStopCam.Name = "btnStopCam" 425 | $System_Drawing_Size = New-Object System.Drawing.Size 426 | $System_Drawing_Size.Width = 75 427 | $System_Drawing_Size.Height = 23 428 | $btnStopCam.Size = $System_Drawing_Size 429 | $btnStopCam.UseVisualStyleBackColor = $True 430 | 431 | $btnStopCam.Text = "Stop" 432 | 433 | $System_Drawing_Point = New-Object System.Drawing.Point 434 | $System_Drawing_Point.X = 13 435 | $System_Drawing_Point.Y = 108 436 | $btnStopCam.Location = $System_Drawing_Point 437 | $btnStopCam.DataBindings.DefaultDataSourceUpdateMode = 0 438 | $btnStopCam.add_Click($handler_btnStopCam_Click) 439 | 440 | $MainForm.Controls.Add($btnStopCam) 441 | 442 | $btnSelectDevice.TabIndex = 2 443 | $btnSelectDevice.Name = "btnSelectDevice" 444 | $System_Drawing_Size = New-Object System.Drawing.Size 445 | $System_Drawing_Size.Width = 75 446 | $System_Drawing_Size.Height = 23 447 | $btnSelectDevice.Size = $System_Drawing_Size 448 | $btnSelectDevice.UseVisualStyleBackColor = $True 449 | 450 | $btnSelectDevice.Text = "Select Device" 451 | 452 | $System_Drawing_Point = New-Object System.Drawing.Point 453 | $System_Drawing_Point.X = 12 454 | $System_Drawing_Point.Y = 42 455 | $btnSelectDevice.Location = $System_Drawing_Point 456 | $btnSelectDevice.DataBindings.DefaultDataSourceUpdateMode = 0 457 | $btnSelectDevice.add_Click($handler_btnSelectDevice_Click) 458 | 459 | $MainForm.Controls.Add($btnSelectDevice) 460 | 461 | $cmbDevices.FormattingEnabled = $True 462 | $System_Drawing_Size = New-Object System.Drawing.Size 463 | $System_Drawing_Size.Width = 242 464 | $System_Drawing_Size.Height = 21 465 | $cmbDevices.Size = $System_Drawing_Size 466 | $cmbDevices.DataBindings.DefaultDataSourceUpdateMode = 0 467 | $cmbDevices.Name = "cmbDevices" 468 | $System_Drawing_Point = New-Object System.Drawing.Point 469 | $System_Drawing_Point.X = 12 470 | $System_Drawing_Point.Y = 11 471 | $cmbDevices.Location = $System_Drawing_Point 472 | $cmbDevices.TabIndex = 1 473 | 474 | $MainForm.Controls.Add($cmbDevices) 475 | 476 | $picCapture.BackColor = [System.Drawing.Color]::FromArgb(255,0,0,0) 477 | $picCapture.TabIndex = 0 478 | $System_Drawing_Size = New-Object System.Drawing.Size 479 | $System_Drawing_Size.Width = 160 480 | $System_Drawing_Size.Height = 120 481 | #$System_Drawing_Size.Width = 260 482 | #$System_Drawing_Size.Height = 220 483 | $picCapture.Size = $System_Drawing_Size 484 | $picCapture.BorderStyle = 2 485 | 486 | 487 | $System_Drawing_Point = New-Object System.Drawing.Point 488 | $System_Drawing_Point.X = 94 489 | $System_Drawing_Point.Y = 42 490 | $picCapture.Location = $System_Drawing_Point 491 | 492 | 493 | $picCapture.TabStop = $False 494 | $picCapture.Name = "picCapture" 495 | $picCapture.DataBindings.DefaultDataSourceUpdateMode = 0 496 | 497 | $MainForm.Controls.Add($picCapture) 498 | 499 | #endregion Generated Form Code 500 | 501 | #Save the initial state of the form 502 | $InitialFormWindowState = $MainForm.WindowState 503 | #Init the OnLoad event to correct the initial state of the form 504 | $MainForm.add_Load($OnLoadForm_StateCorrection) 505 | #Show the Form 506 | $MainForm.ShowDialog()| Out-Null 507 | 508 | } #End Function 509 | 510 | 511 | 512 | Get-WebCamImage -------------------------------------------------------------------------------- /NetflixHack.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 5.0 2 | 3 | # --------------------------------------------------- 4 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\NetflixHack.ps1 5 | # Version: 0.1 6 | # Author: Stefan Stranger 7 | # Date: 02/05/2016 10:04:42 8 | # Description: The Netflix ID Bible – Every Category on Netflix 9 | # Url: http://whatsonnetflix.com/netflix-hacks/the-netflix-id-bible-every-category-on-netflix/ 10 | # One of the complaints we often hear from our users is they actually spend more time looking for content rather than watching it. This quick little Netflix hack aims to help fix this problem. While Netflix is becoming better at predicting what you want to watch, sometimes a specific category can be hard to find. 11 | # How this works is you grab the url from the Netflix search page: 12 | # http://www.netflix.com/WiAltGenre?agid=INSERTNUMBER 13 | # 14 | # New url is http://www.netflix.com/browse/genre/INSERTNUMBER 15 | # 16 | # Simply insert the number of the specific category you want to view. 17 | # Comments: 18 | # Changes: 19 | # Disclaimer: 20 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 21 | # **Always test in your lab first** Do this at your own risk!! 22 | # The author will not be held responsible for any damage you incur when making these changes! 23 | # --------------------------------------------------- 24 | 25 | Function Start-IE 26 | { 27 | [CmdletBinding()] 28 | [OutputType([string])] 29 | Param 30 | ( 31 | # Url to open in browser 32 | [Parameter(Mandatory=$true, 33 | ValueFromPipelineByPropertyName=$true, 34 | Position=0)] 35 | $url) 36 | 37 | Process 38 | { 39 | start $url 40 | } 41 | 42 | } 43 | 44 | # define a sample-driven template describing the data structure: 45 | $template = @' 46 | {Genre*:1365} = {Desciption:Action & Adventure} 47 | {Genre*:77232} = {Description:Asian Action Movies} 48 | '@ 49 | 50 | #Load data from MP Wiki website 51 | $url = 'http://whatsonnetflix.com/netflix-hacks/the-netflix-id-bible-every-category-on-netflix/' 52 | $html = ((Invoke-WebRequest $url).AllElements).innertext 53 | $html | Out-String | 54 | ConvertFrom-String -TemplateContent $template | select * -Unique | 55 | Out-GridView -Title 'Netflix Genre Overview' -PassThru | 56 | Select @{L='Url';E={"http://www.netflix.com/browse/genre/$($_.Genre)"}} | 57 | Start-IE -------------------------------------------------------------------------------- /Pebble_v0.1.ps1: -------------------------------------------------------------------------------- 1 | #Dot library for Pebble by https://github.com/barometz/flint/ 2 | add-type -Path "C:\Users\stefstr\Documents\GitHub\flintlock\flint\flint.dll" 3 | 4 | $pebble = new-object -TypeName flint.Pebble("COM4","[PebbleID]") 5 | 6 | $pebble.Connect() 7 | 8 | $pebble.NotificationMail("PowerShell","Message from PowerShell","How cool is this? :-)") 9 | 10 | #Lock Workstation Function 11 | #http://gallery.technet.microsoft.com/ScriptCenter/a2178d49-79cd-4b3d-918a-47e9c6800262/ 12 | Function Lock-WorkStation { 13 | #Requires -Version 2.0 14 | $signature = @" 15 | [DllImport("user32.dll", SetLastError = true)] 16 | public static extern bool LockWorkStation(); 17 | "@ 18 | 19 | $LockWorkStation = Add-Type -memberDefinition $signature -name "Win32LockWorkStation" -namespace Win32Functions -passthru 20 | $LockWorkStation::LockWorkStation() | Out-Null 21 | } 22 | 23 | while ($true) 24 | { 25 | 26 | if (!($pebble.Alive)) 27 | { 28 | Lock-Workstation 29 | } 30 | 31 | sleep 10 32 | 33 | } 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PowerShell 2 | ========== 3 | 4 | Some powershell scripts for fun and stuff. 5 | 6 | Just a repository to store and share some PowerShell scripts I'm working on. 7 | -------------------------------------------------------------------------------- /TrackDHL.ps1: -------------------------------------------------------------------------------- 1 | $trackingnumber = read-host "Enter DHL Tracking number" 2 | 3 | $url = "http://www.dhl-usa.com/content/us/en/express/tracking.shtml?brand=DHL&AWB=$trackingnumber" 4 | 5 | $result = Invoke-WebRequest -Uri $url 6 | 7 | $result.ParsedHtml.getElementsByTagName("table") | select -expandProperty OuterText -------------------------------------------------------------------------------- /WLANProfiles.ps1: -------------------------------------------------------------------------------- 1 | $result = iex "cmd.exe /c `" netsh wlan show profiles `"" 2 | 3 | # Do some regex magix 4 | # Create new wlan profile object 5 | $WLANProfiles = @() 6 | 7 | 8 | ($result -match "All User Profile.*")| % { 9 | $Object = New-Object PSObject 10 | $Object | add-member Noteproperty "Name" -Value ($_).split(":")[1].substring(1) 11 | $WLANProfiles = $WLANProfiles + $Object 12 | } 13 | 14 | 15 | $resultprofiles = @() 16 | #Get more detailed info on WLAN Profiles 17 | $WLANProfiles | % {write-debug ($_.name); 18 | $profiles = iex "cmd.exe /c `" netsh wlan show profiles name=$($_.name)`"" 19 | $resultprofiles += $profiles 20 | } 21 | 22 | # Do some regex magix again on the results. 23 | $myprofiles =@() 24 | $profileObject = New-Object PSObject 25 | $profileObject | add-member Noteproperty "Name" -Value (($resultprofiles -match "[\d\s]{4}Name.*").split(":")[1] -replace "\A\s+") 26 | $profileObject | add-member Noteproperty "ConnectionMode" -Value (($resultprofiles -match "[\d\s]Connection mode.*").split(":")[1] -replace "\A\s+") 27 | $profileObject | add-member Noteproperty "Authentication" -Value (($resultprofiles -match "[\d\s]Authentication.*").split(":")[1] -replace "\A\s+") 28 | $myprofiles = $myprofiles + $profileObject 29 | 30 | $myprofiles 31 | 32 | #$name = ($resultprofiles -match "[\d\s]{4}Name.*").split(":")[1] -replace "\A\s+" #striped whitespace 33 | 34 | #$connectionmode = ($resultprofiles -match "[\d\s]Connection mode.*").split(":")[1] -replace "\A\s+" #striped whitespace 35 | 36 | #$authentication = ($resultprofiles -match "[\d\s]Authentication.*").split(":")[1] -replace "\A\s+" #striped whitespace 37 | -------------------------------------------------------------------------------- /WinKeys.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: WinKeys.ps1 3 | # Version: 0.2 4 | # Author: Stefan Stranger 5 | # Date: 09-08-2013 6 | # Description: PowerShell Script with Function called Win to run WinKey Combinations from PowerShell 7 | # Comments: Use this in RDP Sessions from within PowerShell 8 | # Video usage url: http://www.youtube.com/watch?v=sI5h3ZGRAtI 9 | # Idea to use PInvoke from StackOverflow 10 | # http://stackoverflow.com/questions/6407584/sendkeys-send-and-windows-key 11 | # http://stackoverflow.com/questions/742262/what-can-i-do-with-c-sharp-and-powershell 12 | # http://ericnelson.wordpress.com/2012/03/12/my-favourite-windows-8-shortcut-keys/ 13 | # --------------------------------------------------- 14 | 15 | 16 | $source = @" 17 | using System; 18 | using System.Collections.Generic; 19 | using System.Linq; 20 | using System.Text; 21 | using System.Threading.Tasks; 22 | using System.Runtime.InteropServices; 23 | using System.Windows.Forms; 24 | 25 | namespace KeyboardSend 26 | { 27 | 28 | 29 | public class KeyboardSend 30 | { 31 | [DllImport("user32.dll")] 32 | public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); 33 | 34 | private const int KEYEVENTF_EXTENDEDKEY = 1; 35 | private const int KEYEVENTF_KEYUP = 2; 36 | 37 | public static void KeyDown(Keys vKey) 38 | { 39 | keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0); 40 | } 41 | 42 | public static void KeyUp(Keys vKey) 43 | { 44 | keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); 45 | } 46 | } 47 | } 48 | 49 | "@ 50 | 51 | Add-Type -TypeDefinition $source -ReferencedAssemblies "System.Windows.Forms" 52 | 53 | Function Win ($Key) 54 | { 55 | [KeyboardSend.KeyboardSend]::KeyDown("LWin") 56 | [KeyboardSend.KeyboardSend]::KeyDown("$Key") 57 | [KeyboardSend.KeyboardSend]::KeyUp("LWin") 58 | 59 | } 60 | 61 | -------------------------------------------------------------------------------- /WinMergeISEAddOn/Module/ISEWinMerge/ISEWinMerge.psd1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanstranger/PowerShell/39abaa832c2108b716c506765d532188df8e3e55/WinMergeISEAddOn/Module/ISEWinMerge/ISEWinMerge.psd1 -------------------------------------------------------------------------------- /WinMergeISEAddOn/Module/ISEWinMerge/ISEWinMerge.psm1: -------------------------------------------------------------------------------- 1 | $isISE = $host.Name -eq 'Windows PowerShell ISE Host' 2 | 3 | if ($isISE) { 4 | if (-not ($Menu = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus | 5 | Where-Object { $_.DisplayName -eq 'WinMerge' })) { 6 | $Menu = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('WinMerge', {Start-WinMerge}, "ALT+W") 7 | } 8 | } 9 | else 10 | { 11 | [System.Windows.Forms.MessageBox]::Show("ISEWinMerge only works in ISE","WinMerge",0,"Warning"); 12 | break 13 | } 14 | 15 | # Configure location of WinMerge 16 | $global:exe = "C:\Program Files (x86)\WinMerge\WinMergeU.exe" 17 | 18 | Function Test-WinMerge ($path = $exe) 19 | { 20 | if (!(Test-Path $path)) 21 | { 22 | $message = "WinMerge not found in C:\Program Files (x86)\WinMerge" + [System.Environment]::NewLine + [System.Environment]::NewLine +"Install WinMerge or change path in Module"; 23 | [System.Windows.Forms.MessageBox]::Show($message,"WinMerge",0,"Warning"); 24 | break 25 | } 26 | 27 | } 28 | 29 | Function Start-WinMerge 30 | { 31 | # Variables 32 | $global:tabs = $PSISe.PowerShellTabs.Files 33 | $totalrows = $tabs.count + 3 34 | $tabsrow = 1 35 | 36 | #WPF Object Styles 37 | Set-UIStyle "L1" @{ FontFamily = "Helvetica"; FontSize = 14; FontWeight = "Bold"; ForeGround = "#6E0504" } 38 | Set-UIStyle "C1" @{ FontFamily = "Helvetica"; FontSize = 12 } 39 | 40 | # Grid Style 41 | $gridparam = @{ 42 | Name = "WinMerge" 43 | ControlName = "Show-ISETab" 44 | Background = '#FFD82F' #WinMerge color 45 | Rows = $totalrows 46 | Columns = 2 47 | } 48 | 49 | 50 | New-Grid @gridparam -Show -On_Loaded { 51 | $window.title = "WinMerge ISE add-on" } { 52 | New-Label "Select 2 Open ISE tabs" -Row 0 -Column 0 -VisualStyle L1 53 | 54 | #Add Checkboxes for open ISE tabs 55 | foreach ($tab in $tabs) 56 | 57 | { 58 | #Remove non ascii characters from open filenames. Checkbox objects cannot have non-ascii characters in their name. 59 | $name = ($tab.Displayname) -creplace '[^a-zA-Z0-9]', '' 60 | New-Checkbox -Name $name -Content $tab.displayname -DataContext $tab -BorderThickness 1 -Row $tabsrow -Margin 2 -VisualStyle C1 61 | $tabsrow++ 62 | } 63 | 64 | #Ok and Cancel Buttons 65 | New-UniformGrid -Row $totalrows -ColumnSpan 2 -Columns 2 { 66 | 67 | Button "Ok" -On_Click { 68 | #Retrieve checkbox variables. 69 | $checkboxes = get-variable 70 | $selected = ($checkboxes.Value | ? ischecked -eq "$true").count 71 | 72 | #Check if only 2 tabs in WPF form are selected. 73 | if ($selected -ne 2) 74 | { 75 | [System.Windows.Forms.MessageBox]::Show("Only 2 checkboxes allowed!","WinMerge",0,"Warning"); 76 | $Window | Close-Control 77 | } 78 | else 79 | { 80 | #Check selected Checkboxes 81 | if ($checkboxes.Value | ? ischecked -eq "$true") 82 | { 83 | $mychecks = ($checkboxes.Value | ? ischecked -eq "$true").Name 84 | [array]$params = @() 85 | foreach ($check in $mychecks) 86 | { 87 | $FullPath = ($tabs | ? {($_.Displayname -creplace '[^a-zA-Z0-9]', '') -eq $($check)}) 88 | $params += $FullPath.Fullpath 89 | 90 | } 91 | $param1 = [string]$params[0] 92 | $param2 = [string]$params[1] 93 | #Call WinMerge application 94 | $exe = "C:\Program Files (x86)\WinMerge\WinMergeU.exe" 95 | &$exe $param1 $param2 96 | 97 | } 98 | else 99 | { 100 | [System.Windows.Forms.MessageBox]::Show("Shoot","MyChecks",0,"Warning"); 101 | $parent | Set-UIValue -passThru | Close-Control 102 | } 103 | } 104 | 105 | } -IsDefault -Margin 5 -Row $totalrows -Column 0 #-ColumnSpan 1 106 | 107 | Button "Cancel" -On_Click { 108 | $parent | Set-UIValue -passThru | Close-Control 109 | } -IsDefault -Margin 5 -Row $totalrows -Column 1 #-ColumnSpan 2 110 | } 111 | } 112 | } 113 | 114 | 115 | #Check if WinMerge application is installed 116 | Test-WinMerge 117 | 118 | Export-ModuleMember -Function * -Alias * -------------------------------------------------------------------------------- /WinMergeISEAddOn/README.md: -------------------------------------------------------------------------------- 1 | # Powershell WinMerge ISE Add-On 2 | - - - 3 | This ISE Add-On adds integration with the WINMerge application into the ISE. 4 | 5 | For more information about WinMerge go to: http://winmerge.org/ 6 | 7 | 02/12/2015: - Initial version 8 | 9 | 02/14/2015: - Changed location default install WinMerge. Some visual improvements 10 | 11 | ![ScreenShot](https://raw.githubusercontent.com/stefanstranger/PowerShell/master/WinMergeISEAddOn/WinMergeWPF_opt.gif) 12 | 13 | # Install 14 | First install WinMerge using PowerShell OneGet or manually from http://winmerge.org 15 | 16 | Install ShowUI module from https://showui.codeplex.com/ 17 | 18 | Change the following part of the WINMerge_WPF.ps1 file 19 | .. 20 | $exe = "C:\Program Files (x86)\WinMerge\WinMergeU.exe" 21 | .. 22 | 23 | Run .\WinMerge-ISEAddOn.ps1 24 | -------------------------------------------------------------------------------- /WinMergeISEAddOn/WINMerge_WPF.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\WinMergeISEAddOn\WINMerge_WPF.ps1 3 | # Version: 0.2 4 | # Author: Stefan Stranger 5 | # Date: 02/14/2015 14:50:36 6 | # Description: PowerShell script to generate WPF form for WinMerge-ISEAddOn 7 | # Comments: Manually install WinMerge 8 | # Changes: Changed path to WinMerge. 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | ipmo showui 15 | 16 | # Variables 17 | $tabs = $PSISe.PowerShellTabs.Files 18 | $totalrows = $tabs.count + 3 19 | $tabsrow = 1 20 | #Configure the path the location of WinMergeU.exe application. 21 | $exe = "C:\Program Files (x86)\WinMerge\WinMergeU.exe" 22 | 23 | #WPF Object Styles 24 | Set-UIStyle "L1" @{ FontFamily = "Helvetica"; FontSize = 14; FontWeight = "Bold"; ForeGround = "#6E0504" } 25 | Set-UIStyle "C1" @{ FontFamily = "Helvetica"; FontSize = 12 } 26 | 27 | # Grid Style 28 | $gridparam = @{ 29 | Name = "WinMerge" 30 | ControlName = "Show-ISETab" 31 | Background = '#FFD82F' #WinMerge color 32 | Rows = $totalrows 33 | Columns = 2 34 | } 35 | 36 | 37 | New-Grid @gridparam -Show -On_Loaded { 38 | $window.title = "WinMerge ISE add-on" } { 39 | New-Label "Select 2 Open ISE tabs" -Row 0 -Column 0 -VisualStyle L1 40 | 41 | #Add Checkboxes for open ISE tabs 42 | foreach ($tab in $tabs) 43 | 44 | { 45 | #Remove non ascii characters from open filenames. Checkbox objects cannot have non-ascii characters in their name. 46 | $name = ($tab.Displayname) -creplace '[^a-zA-Z0-9]', '' 47 | New-Checkbox -Name $name -Content $tab.displayname -DataContext $tab -BorderThickness 1 -Row $tabsrow -Margin 2 -VisualStyle C1 48 | $tabsrow++ 49 | } 50 | 51 | #Ok and Cancel Buttons 52 | New-UniformGrid -Row $totalrows -ColumnSpan 2 -Columns 2 { 53 | 54 | Button "Ok" -On_Click { 55 | #Retrieve checkbox variables. 56 | $checkboxes = get-variable 57 | $selected = ($checkboxes.Value | ? ischecked -eq "$true").count 58 | 59 | #Check if only 2 tabs in WPF form are selected. 60 | if ($selected -ne 2) 61 | { 62 | [System.Windows.Forms.MessageBox]::Show("Only 2 checkboxes allowed!","WinMerge",0,"Warning"); 63 | $Window | Close-Control 64 | } 65 | else 66 | { 67 | #Check selected Checkboxes 68 | if ($checkboxes.Value | ? ischecked -eq "$true") 69 | { 70 | $mychecks = ($checkboxes.Value | ? ischecked -eq "$true").Name 71 | [array]$params = @() 72 | foreach ($check in $mychecks) 73 | { 74 | $FullPath = ($tabs | ? {($_.Displayname -creplace '[^a-zA-Z0-9]', '') -eq $($check)}) 75 | $params += $FullPath.Fullpath 76 | 77 | } 78 | $param1 = [string]$params[0] 79 | $param2 = [string]$params[1] 80 | #Call WinMerge application 81 | $exe = "C:\Program Files (x86)\WinMerge\WinMergeU.exe" 82 | &$exe $param1 $param2 83 | 84 | } 85 | else 86 | { 87 | [System.Windows.Forms.MessageBox]::Show("Shoot","MyChecks",0,"Warning"); 88 | $parent | Set-UIValue -passThru | Close-Control 89 | } 90 | } 91 | 92 | } -IsDefault -Margin 5 -Row $totalrows -Column 0 #-ColumnSpan 1 93 | 94 | Button "Cancel" -On_Click { 95 | $parent | Set-UIValue -passThru | Close-Control 96 | } -IsDefault -Margin 5 -Row $totalrows -Column 1 #-ColumnSpan 2 97 | } 98 | } -------------------------------------------------------------------------------- /WinMergeISEAddOn/WinMerge-ISEAddOn.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------- 2 | # Script: C:\Users\stefstr\Documents\GitHub\PowerShell\WinMergeISEAddOn\WinMerge-ISEAddOn.ps1 3 | # Version: 0.1 4 | # Author: Stefan Stranger 5 | # Date: 02/12/2015 14:51:50 6 | # Description: WINMerge ISE AddOn 7 | # Comments: 8 | # Changes: 9 | # Disclaimer: 10 | # This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 11 | # **Always test in your lab first** Do this at your own risk!! 12 | # The author will not be held responsible for any damage you incur when making these changes! 13 | # --------------------------------------------------- 14 | 15 | [void]$psise. 16 | CurrentPowerShellTab. 17 | AddOnsMenu. 18 | SubMenus. 19 | Add("Open WINMERGE", 20 | {. C:\Users\stefstr\Documents\GitHub\PowerShell\WinMergeISEAddOn\WINMerge_WPF.ps1} , "ALT+W") -------------------------------------------------------------------------------- /WinMergeISEAddOn/WinMergeWPF_opt.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanstranger/PowerShell/39abaa832c2108b716c506765d532188df8e3e55/WinMergeISEAddOn/WinMergeWPF_opt.gif -------------------------------------------------------------------------------- /WinMergeISEAddOn/isewinmergemodule.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanstranger/PowerShell/39abaa832c2108b716c506765d532188df8e3e55/WinMergeISEAddOn/isewinmergemodule.gif --------------------------------------------------------------------------------