├── _config.yml
├── Others
├── csvloop
│ ├── test.csv
│ └── Read-CSVFileAndProcess.ps1
├── Get-PowerConfigurationActive.ps1
├── Write-HistoryToFile.ps1
├── Measure-Commands.ps1
├── Format-Easy.ps1
├── Get-LoggedOnUsers.ps1
├── Get-PowerStateRunning.ps1
├── Get-RunningServicesShort.ps1
├── Get-ADUserPermission.ps1
├── Get-StoppedServices.ps1
├── Get-RebootTime.ps1
├── Get-GetCommandsWithComputerNameParameter.ps1
├── Get-Unzip.ps1
├── Get-FilesInDirectoryRecursevly.ps1
├── Show-WindowsNotification.ps1
├── Get-FileEncoding.ps1
├── Get-RemotingCommands.ps1
├── Create-BasicForm.ps1
├── Set-PowerConfigurationActive.ps1
├── Set-Wallpaper.ps1
├── Send-EmailTest.ps1
├── RenameAndMoveChildItemFileToParentDir.ps1
├── Get-ServiceStartTime.ps1
├── Parse-Website.psm1
└── Show-Calendar.ps1
├── Server
├── 1Get-WindowsFeatures.ps1
├── Get-SystemVersion.ps1
├── 2Rename-Computer.ps1
├── 4Install-AddsForest.ps1
├── 6Enable-SQLPort1433.ps1
├── 3Install-WindowsFeatureBasic.ps1
├── Get-.NetVersionLatest.ps1
├── 5Set-PasswordNeverExpires.ps1
├── Get-.NetVersion.ps1
├── _Setup-InitalServer.ps1
├── Microsoft_Dynamics_AX_2012_Prerequiste_Check_Report_Downloads.ps1
└── Set-UserFlag.ps1
├── Remote
├── Test-PSSession.ps1
├── Test-AccessRemoteSystem.ps1
├── Test-InvokeRemoteCommand.ps1
├── Start-MstcWithCred.ps1
├── Connect-RDP.ps1
├── Collect-Perf.ps1
├── New-DataCollectorSet.ps1
└── Connect-Mstsc.ps1
├── Azure
├── Get-AzureRmVmRunning.ps1
├── Get-AzureRmVmStatuses.ps1
├── Get-AzureRMVMStatus.ps1
└── Open-AzureVmRDP.ps1
├── Hyper-V
├── Connect-VM.ps1
├── New-Image.ps1
├── Create-HyperVClienServer.ps1
└── Create-HyperV.ps1
├── GUI
└── HTA
│ ├── default.vbs
│ └── default.hta
├── Audit
└── Get-AuditPolicyCategories.ps1
├── WiFi
├── Get-WifiSSIDAndPasswordWrapper.ps1
└── Get-WifiSSIDAndPassword.ps1
├── Registry
├── Search-RegistryByProperty.ps1
├── Search-RegistrySubtreeByProperty.ps1
└── search-registry.ps1
├── Office
├── Get-WordXmlProperties.ps1
└── Get-WordProperties.ps1
├── MachineLearning
└── Train-ModelsParallel.ps1
└── README.md
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-hacker
--------------------------------------------------------------------------------
/Others/csvloop/test.csv:
--------------------------------------------------------------------------------
1 | test1
2 | test2
3 | test3
--------------------------------------------------------------------------------
/Server/1Get-WindowsFeatures.ps1:
--------------------------------------------------------------------------------
1 | Get-WindowsFeature
--------------------------------------------------------------------------------
/Server/Get-SystemVersion.ps1:
--------------------------------------------------------------------------------
1 | $PSVersionTable.CLRVersion
--------------------------------------------------------------------------------
/Others/Get-PowerConfigurationActive.ps1:
--------------------------------------------------------------------------------
1 | powercfg /GETACTIVESCHEME
--------------------------------------------------------------------------------
/Server/2Rename-Computer.ps1:
--------------------------------------------------------------------------------
1 | Rename-Computer -NewName "Demo" -restart
--------------------------------------------------------------------------------
/Others/Write-HistoryToFile.ps1:
--------------------------------------------------------------------------------
1 | gethistory | out-file c:\Source\Repos\hist.txt
--------------------------------------------------------------------------------
/Server/4Install-AddsForest.ps1:
--------------------------------------------------------------------------------
1 | Install-ADDSForest -DomainName “CONTOSO.com”
--------------------------------------------------------------------------------
/Remote/Test-PSSession.ps1:
--------------------------------------------------------------------------------
1 | Enter-PSSession -ComputerName DE-LOANER394 -Credential kastolz
--------------------------------------------------------------------------------
/Others/Measure-Commands.ps1:
--------------------------------------------------------------------------------
1 | Measure-Command -Expression { $ScriptBlog } -Argument $ScriptBlog
--------------------------------------------------------------------------------
/Azure/Get-AzureRmVmRunning.ps1:
--------------------------------------------------------------------------------
1 | get-azurermvm -Status | Where-Object PowerState -match "running"
--------------------------------------------------------------------------------
/Hyper-V/Connect-VM.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkWarneke/PowerShell/HEAD/Hyper-V/Connect-VM.ps1
--------------------------------------------------------------------------------
/Others/Format-Easy.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkWarneke/PowerShell/HEAD/Others/Format-Easy.ps1
--------------------------------------------------------------------------------
/Remote/Test-AccessRemoteSystem.ps1:
--------------------------------------------------------------------------------
1 | $name = $(Get-WmiObject Win32_Computersystem).name
2 | Test-WsMan $name
--------------------------------------------------------------------------------
/Others/Get-LoggedOnUsers.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkWarneke/PowerShell/HEAD/Others/Get-LoggedOnUsers.ps1
--------------------------------------------------------------------------------
/GUI/HTA/default.vbs:
--------------------------------------------------------------------------------
1 |
2 | Sub Test()
3 | msgbox "Test"
4 | End Sub
5 |
6 | Sub Initialize()
7 |
8 | End Sub
--------------------------------------------------------------------------------
/Others/Get-PowerStateRunning.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkWarneke/PowerShell/HEAD/Others/Get-PowerStateRunning.ps1
--------------------------------------------------------------------------------
/Remote/Test-InvokeRemoteCommand.ps1:
--------------------------------------------------------------------------------
1 | Invoke-Command -ComputerName DE-LOANER394 -ScriptBlock { ipconfig } -credential kastolz
--------------------------------------------------------------------------------
/Audit/Get-AuditPolicyCategories.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkWarneke/PowerShell/HEAD/Audit/Get-AuditPolicyCategories.ps1
--------------------------------------------------------------------------------
/Others/Get-RunningServicesShort.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkWarneke/PowerShell/HEAD/Others/Get-RunningServicesShort.ps1
--------------------------------------------------------------------------------
/Others/Get-ADUserPermission.ps1:
--------------------------------------------------------------------------------
1 | Import-Module ActiveDirectory
2 | (Get-ACL "AD:$((Get-ADUser Twon.of.An).distinguishedname)").access
--------------------------------------------------------------------------------
/Azure/Get-AzureRmVmStatuses.ps1:
--------------------------------------------------------------------------------
1 | Get-AzureRmVm | Get-AzureRmVm -Status | select ResourceGroupName, Name, @{n="Status"; e={$_.Statuses[1].DisplayStatus}}
--------------------------------------------------------------------------------
/Others/Get-StoppedServices.ps1:
--------------------------------------------------------------------------------
1 | get-service | where-object Status -eq 'Stopped' | select-object Status, Name, Displayname | export-csv C:\Source\test.csv
--------------------------------------------------------------------------------
/Server/6Enable-SQLPort1433.ps1:
--------------------------------------------------------------------------------
1 | netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
--------------------------------------------------------------------------------
/Others/Get-RebootTime.ps1:
--------------------------------------------------------------------------------
1 | Get-EventLog -log system -newest 1000 | where-object eventid -eq '1074' | format-table machinename, username, timegenerated -autosize
--------------------------------------------------------------------------------
/Others/Get-GetCommandsWithComputerNameParameter.ps1:
--------------------------------------------------------------------------------
1 | Get-Command | where { $_.parameters.keys -contains "ComputerName" -and $_.parameters.keys -notcontains "Session"}
--------------------------------------------------------------------------------
/Server/3Install-WindowsFeatureBasic.ps1:
--------------------------------------------------------------------------------
1 | $Name = (Get-WMIObject Win32_ComputerSystem).name
2 |
3 | Install-WindowsFeature -Name DNS, AD-Domain-Services -ComputerName $Name
--------------------------------------------------------------------------------
/Server/Get-.NetVersionLatest.ps1:
--------------------------------------------------------------------------------
1 | gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' |
2 | sort pschildname -des |
3 | select -fi 1 -exp pschildname
--------------------------------------------------------------------------------
/WiFi/Get-WifiSSIDAndPasswordWrapper.ps1:
--------------------------------------------------------------------------------
1 | iex(new-object system.net.webclient).downloadstring("file://C:\Users\mawarnek\OneDrive - Microsoft
2 | \scripts\powershell\Get-WifiSSIDAndPassword.ps1")
--------------------------------------------------------------------------------
/Others/Get-Unzip.ps1:
--------------------------------------------------------------------------------
1 | Add-Type -AssemblyName System.IO.Compression.FileSystem
2 | function Get-Unzip
3 | {
4 | param([string]$zipfile, [string]$outpath)
5 |
6 | [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
7 | }
--------------------------------------------------------------------------------
/Server/5Set-PasswordNeverExpires.ps1:
--------------------------------------------------------------------------------
1 | wmic useraccount
2 |
3 | $user = [adsi]"WinNT://$env:computername/administrator"
4 | $user.UserFlags.value = $user.UserFlags.value -bor 0x10000
5 | $user.CommitChanges()
6 |
7 | # check PasswordExpires
8 | wmic useraccount
9 |
--------------------------------------------------------------------------------
/Remote/Start-MstcWithCred.ps1:
--------------------------------------------------------------------------------
1 | cmdkey /generic:DOMAIN/"computername or IP" /user:"username" /pass:"password"
2 | # call RDP connection using
3 | Start-Process -FilePath "$env:windir\system32\mstsc.exe" -ArgumentList "/v:computer name/IP" -Wait
4 | # If you want to delete the credentials run
5 | cmdkey /delete:DOMAIN/"Computer name or IP"
--------------------------------------------------------------------------------
/Registry/Search-RegistryByProperty.ps1:
--------------------------------------------------------------------------------
1 | $RegistryPath = "HKLM:\SOFTWARE"
2 | $SearchProperty = "EnvironmentPathNode"
3 |
4 | Get-ChildItem -Path $RegistryPath | foreach {
5 | $RegistryEntry = $_.Name
6 | Get-ItemProperty -Path $RegistryEntry | foreach {
7 | Write-Host $_
8 | }
9 | }
10 |
11 | # NOT WORKING
--------------------------------------------------------------------------------
/Azure/Get-AzureRMVMStatus.ps1:
--------------------------------------------------------------------------------
1 | [CmdletBinding()]
2 | Param(
3 | [Parameter(Mandatory=$True)]
4 | [string]$Name,
5 | [Parameter(Mandatory=$True)]
6 | [string]$ResourceGroupName
7 | )
8 | Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $Name -Status | `
9 | select -ExpandProperty Statuses | `
10 | ?{ $_.Code -match "PowerState" } | `
11 | select -ExpandProperty DisplayStatus
--------------------------------------------------------------------------------
/Others/Get-FilesInDirectoryRecursevly.ps1:
--------------------------------------------------------------------------------
1 | function GetFiles($path = $pwd, [string[]]$exclude)
2 | {
3 | foreach ($item in Get-ChildItem $path)
4 | {
5 |
6 | if (Test-Path $item.FullName -PathType Container)
7 | {
8 | $item
9 | GetFiles $item.FullName $exclude
10 | }
11 | else
12 | {
13 | $item
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/Office/Get-WordXmlProperties.ps1:
--------------------------------------------------------------------------------
1 | Add-Type -AssemblyName System.IO.Compression.FileSystem
2 |
3 | $filename = "C:\Users\mawarnek\OneDrive - Microsoft\Products\ESAE\ESAEv3_Build_Implementation_Guide-Appendices.docx"
4 |
5 | $zip = [System.IO.Compression.ZipFile]::Open($filename, 'Read')
6 | $propsentry = $zip.GetEntry('docProps/app.xml')
7 | If ($propsentry -ne $null) {
8 | $stream = $propsentry.Open()
9 | $reader = New-Object System.IO.StreamReader $stream
10 | $content = $reader.ReadToEnd()
11 | $xmldoc = [xml]$content
12 | $xmldoc.Properties
13 | }
14 | $zip.Dispose()
--------------------------------------------------------------------------------
/Azure/Open-AzureVmRDP.ps1:
--------------------------------------------------------------------------------
1 | function rdpvm ($ServiceName,$Name) {
2 | $vm = (Get-AzureVM -ServiceName $ServiceName -Name $Name)
3 | if($vm -and $vm.InstanceStatus -eq 'ReadyRole') {
4 | $rdp = (Get-AzureEndpoint -VM $vm | where { $_.LocalPort -eq 3389})
5 | $fqdn = (New-Object System.URI $vm.DNSName).Authority
6 | $port = $rdp.Port
7 | Write-Verbose "Opening Remote Desktop Session with $($fqdn):$($port)..."
8 | Start-Process "mstsc" -ArgumentList "/V:$($fqdn):$($port)"
9 | }
10 | else {
11 | Write-Warning "The VM $($vm.Name) is not running ($($vm.InstanceStatus)). You should start it first"
12 | }
13 | }
--------------------------------------------------------------------------------
/Others/Show-WindowsNotification.ps1:
--------------------------------------------------------------------------------
1 |
2 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
3 |
4 | $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
5 |
6 | # $objNotifyIcon.Icon = "C:\Scripts\Forms\Folder.ico"
7 | $objNotifyIcon.BalloonTipIcon = "Info"
8 | $objNotifyIcon.BalloonTipText = "Retrieving files from C:\Windows."
9 | $objNotifyIcon.BalloonTipTitle = "Retrieving Files"
10 |
11 | $objNotifyIcon.Visible = $True
12 | $objNotifyIcon.ShowBalloonTip(10000)
13 |
14 | Get-ChildItem C:\Windows
15 |
16 | $objNotifyIcon.BalloonTipText = "The script has finished running."
17 | $objNotifyIcon.BalloonTipTitle = "Files retrieved."
18 |
19 | $objNotifyIcon.Visible = $True
20 | $objNotifyIcon.ShowBalloonTip(10000)
--------------------------------------------------------------------------------
/Server/Get-.NetVersion.ps1:
--------------------------------------------------------------------------------
1 | Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
2 | Get-ItemProperty -name Version,Release -EA 0 |
3 | Where { $_.PSChildName -match '^(?!S)\p{L}'} |
4 | Select PSChildName, Version, Release, @{
5 | name="Product"
6 | expression={
7 | switch -regex ($_.Release) {
8 | "378389" { [Version]"4.5" }
9 | "378675|378758" { [Version]"4.5.1" }
10 | "379893" { [Version]"4.5.2" }
11 | "393295|393297" { [Version]"4.6" }
12 | "394254|394271" { [Version]"4.6.1" }
13 | "394802|394806" { [Version]"4.6.2" }
14 | "460798" { [Version]"4.7" }
15 | {$_ -gt 460798} { [Version]"Undocumented 4.7 or higher, please update script" }
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/Server/_Setup-InitalServer.ps1:
--------------------------------------------------------------------------------
1 | Get-WindowsFeature
2 | $Name = (Get-WMIObject Win32_ComputerSystem).name
3 |
4 | Rename-Computer -NewName "Demo" -restart
5 |
6 | $Name = (Get-WMIObject Win32_ComputerSystem).name
7 |
8 | Install-WindowsFeature -Name DNS, AD-Domain-Services -ComputerName $Name
9 |
10 | Install-ADDSForest -DomainName “CONTOSO.com”
11 |
12 | Write-Verbose "Install .NET Framework 3.5 from WinSrv12 ISO"
13 | Install-WindowsFeature -Name Net-Framework-Feature -Source D:\sources\sxs
14 |
15 |
16 | # install sql server
17 |
18 | netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
19 |
20 |
21 | # install sp1 for visual studio download
22 |
23 | Install-WindowsFeature Windows-Identiy-Foundation
--------------------------------------------------------------------------------
/Office/Get-WordProperties.ps1:
--------------------------------------------------------------------------------
1 | $application = New-Object -ComObject word.application
2 |
3 | $application.Visible = $false
4 | $document = $application.documents.open("C:\Users\mawarnek\OneDrive - Microsoft\Products\ESAE\ESAEv3_Build_Implementation_Guide-Appendices.docx")
5 | $binding = "System.Reflection.BindingFlags" -as [type]
6 | $properties = $document.BuiltInDocumentPropertiese
7 |
8 | foreach ($property in $properties) {
9 | $pn = [System.__ComObject].invokemember("name", $binding::GetProperty, $null, $property, $null)
10 | trap [system.exception] {
11 | write-host -foreground blue "Value not found for $pn"
12 | continue
13 | }
14 | "$pn`: " +
15 | [System.__ComObject].invokemember("value", $binding::GetProperty, $null, $property, $null)
16 |
17 | }
18 | $application.quit()
--------------------------------------------------------------------------------
/MachineLearning/Train-ModelsParallel.ps1:
--------------------------------------------------------------------------------
1 | ## Run Model Training
2 | Start-Job -Name Subcat1 -ScriptBlock {
3 | ### Train Subcat external
4 | az ml experiment submit -c dbottomldsvm -p "C:\Users\$env:username\Documents\AzureML\tbottomlproject\" --wait code\2train_subcat.py --task 1
5 | }
6 | Start-Job -Name Subcat2 -ScriptBlock {
7 | ### Train Subcat internal
8 | az ml experiment submit -c dbottomldsvm -p "C:\Users\$env:username\Documents\AzureML\tbottomlproject\" --wait code\2train_subcat.py --task 2
9 | }
10 | Start-Job -Name Prio -ScriptBlock {
11 | ### Train Priority
12 | az ml experiment submit -c dbottomldsvm -p "C:\Users\$env:username\Documents\AzureML\tbottomlproject\" --wait code\2train_priority.py
13 | }
14 |
15 | #Wait for all jobs
16 | Get-Job | Wait-Job
17 | #Get all job results
18 | Get-Job | Receive-Job | Out-GridView
--------------------------------------------------------------------------------
/Others/Get-FileEncoding.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf Gets files that are UTF-8 with BOM
3 | #>
4 | function Get-FileEncoding
5 | {
6 | [CmdletBinding()] Param (
7 | [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
8 | )
9 |
10 | [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path
11 |
12 | if($byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf)
13 | {Write-Output 'UTF-8-BOM'}
14 | elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
15 | { Write-Output 'Unicode' }
16 | elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
17 | { Write-Output 'UTF32' }
18 | elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
19 | { Write-Output 'UTF7'}
20 | else
21 | { Write-Output 'ASCII or UTF-8' }
22 | }
--------------------------------------------------------------------------------
/Others/Get-RemotingCommands.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .Synopsis
3 | Get a list of possible remoting PowerShell commands
4 |
5 | .Description
6 | Gets a list of possible remotin PowerShell commands based on the ComputerName and Session property parameter
7 |
8 | .Parameter
9 | parameterDescription
10 |
11 | .Example
12 | eampleDesciption
13 |
14 | #>
15 |
16 |
17 | <#
18 | DISCLAIMER:
19 |
20 | Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability or fitness for a particular purpose.
21 | This mail message assumes that you are familiar with the programming language that is being demonstrated and the tools that are used to create and debug procedures.
22 | #requires -version 2.0
23 |
24 | Author: Mark Warneke
25 | Created: 14-Apr-17
26 | #>
27 |
28 | Get-Command | where { $_.parameters.keys -contains "ComputerName" -and $_.parameters.keys -notcontains "Session"}
--------------------------------------------------------------------------------
/GUI/HTA/default.hta:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Simple
8 |
10 |
24 |
28 |
29 |
30 |
31 |
32 |
33 |
38 |
39 |
--------------------------------------------------------------------------------
/Remote/Connect-RDP.ps1:
--------------------------------------------------------------------------------
1 | function Connect-RDP {
2 |
3 | param (
4 | [Parameter(Mandatory=$true)]
5 | $ComputerName,
6 |
7 | [System.Management.Automation.Credential()]
8 | $Credential
9 | )
10 |
11 | # take each computername and process it individually
12 | $ComputerName | ForEach-Object {
13 |
14 | # if the user has submitted a credential, store it
15 | # safely using cmdkey.exe for the given connection
16 | if ($PSBoundParameters.ContainsKey('Credential'))
17 | {
18 | # extract username and password from credential
19 | $User = $Credential.UserName
20 | $Password = $Credential.GetNetworkCredential().Password
21 |
22 | # save information using cmdkey.exe
23 | cmdkey.exe /generic:$_ /user:$User /pass:$Password
24 | }
25 |
26 | # initiate the RDP connection
27 | # connection will automatically use cached credentials
28 | # if there are no cached credentials, you will have to log on
29 | # manually, so on first use, make sure you use -Credential to submit
30 | # logon credential
31 |
32 | mstsc.exe /v $_ /f
33 | }
34 | }
--------------------------------------------------------------------------------
/Others/csvloop/Read-CSVFileAndProcess.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | DISCLAIMER:
3 |
4 | Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability or fitness for a particular purpose.
5 | This mail message assumes that you are familiar with the programming language that is being demonstrated and the tools that are used to create and debug procedures.
6 | #requires -version 2.0
7 |
8 | Author: Mark Warneke
9 | Created: 13-Apr-17
10 | #>
11 |
12 | <#
13 | .Synopsis
14 | synopsis
15 |
16 | .Description
17 | Short script to load csv into an array and process this information
18 |
19 | .Parameter CsvPath
20 | Path to the CSV file
21 |
22 | .Example
23 |
24 |
25 | #>
26 |
27 |
28 | function Read-CSVFileAndProcess {
29 | [CmdletBinding()]
30 | param (
31 | [Parameter (
32 | Mandatory = $True,
33 | ValueFromPipelineByPropertyName = $True
34 | )]
35 | [string] $CsvPath
36 | )
37 |
38 |
39 | $Dirs = Import-Csv $CsvPath
40 |
41 | foreach ($dir in $Dirs) {
42 | $number = $dir.sub(4,4)
43 | Write-Host $dir
44 | $new = New-Item $dir -type directory -value $number+1
45 | "test" > $new
46 | }
47 |
48 | }
49 |
50 | export-modulemember -function Read-CSVFileAndProcess
--------------------------------------------------------------------------------
/Server/Microsoft_Dynamics_AX_2012_Prerequiste_Check_Report_Downloads.ps1:
--------------------------------------------------------------------------------
1 |
2 | # Download and install the Open XML SDK for Microsoft Office from
3 | http://go.microsoft.com/fwlink/?LinkID=186355
4 |
5 | # You can download and install the Analysis Management Objects from
6 | http://go.microsoft.com/fwlink/?LinkID=188448
7 |
8 | # Download and install the Microsoft Visual C++ 2008 SP1 Redistributable Package from
9 | http://go.microsoft.com/fwlink/?LinkId=158917
10 |
11 | # Download and install the Microsoft Visual C++ 2008 SP1 Redistributable Package from
12 | http://go.microsoft.com/fwlink/?LinkId=158918
13 |
14 | # Download and install the Microsoft Visual C++ 2012 Redistributable Package from
15 | http://go.microsoft.com/fwlink/?LinkId=386529
16 |
17 | # Download and install Microsoft Visual Studio 2010 Service Pack 1 from
18 | http://go.microsoft.com/fwlink/?LinkId=215027
19 |
20 | # Download and install the Microsoft Chart Controls for Microsoft .NET Framework 3.5 from
21 | http://go.microsoft.com/fwlink/?LinkId=236067
22 |
23 | https://www.microsoft.com/en-us/download/confirmation.aspx?id=2092
24 |
25 |
26 | # Visual Studio 2010 SP1
27 | # NOT WORKIN http://go.microsoft.com/fwlink/?LinkId=215027
28 | http://www.microsoft.com/en-us/download/details.aspx?id=21835
29 |
30 | # just update https://www.microsoft.com/en-us/download/details.aspx?id=44908
31 | # http://www.microsoft.com/en-us/download/details.aspx?id=44908
32 |
--------------------------------------------------------------------------------
/WiFi/Get-WifiSSIDAndPassword.ps1:
--------------------------------------------------------------------------------
1 | #Make a list with all WiFi SSID's and passwords stored locally on Windows OS.
2 |
3 | $output = netsh.exe wlan show profiles
4 | $profileRows = $output | Select-String -Pattern 'All User Profile'
5 | $profileNames = New-Object System.Collections.ArrayList
6 |
7 | #for each profile name get the SSID and password
8 | for($i = 0; $i -lt $profileRows.Count; $i++){
9 | $profileName = ($profileRows[$i] -split ":")[-1].Trim()
10 |
11 | $profileOutput = netsh.exe wlan show profiles name="$profileName" key=clear
12 |
13 | $SSIDSearchResult = $profileOutput| Select-String -Pattern 'SSID Name'
14 | $profileSSID = ($SSIDSearchResult -split ":")[-1].Trim() -replace '"'
15 |
16 | $passwordSearchResult = $profileOutput| Select-String -Pattern 'Key Content'
17 | if($passwordSearchResult){
18 | $profilePw = ($passwordSearchResult -split ":")[-1].Trim()
19 | } else {
20 | $profilePw = ''
21 | }
22 |
23 | $networkObject = New-Object -TypeName psobject -Property @{
24 | ProfileName = $profileName
25 | SSID = $profileSSID
26 | Password = $profilePw
27 | }
28 | $profileNames.Add($networkObject)
29 | }
30 |
31 | $profileNames | Sort-Object ProfileName | Select-Object ProfileName, SSID, Password
32 |
33 | #blog help source: https://blogs.technet.microsoft.com/heyscriptingguy/2015/11/23/get-wireless-network-ssid-and-password-with-powershell/
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PowerShell
2 | Simple powershell scripts for learning and sharing purposes.
3 | These scripts are my personal collection.
4 | The scripts are not getting revised and/or maintained by Microsoft, thus should NOT be used in any production environment.
5 |
6 | # DISCLAIMER:
7 |
8 | This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment.
9 |
10 | THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED AS IS
11 | WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
12 | TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
13 |
14 | We grant You a nonexclusive, royalty-free right to use and modify the Sample Code
15 | and to reproduce and distribute the object code form of the Sample Code, provided
16 | that You agree:
17 | 1. to not use Our name, logo, or trademarks to market Your software
18 | product in which the Sample Code is embedded;
19 | 2. to include a valid copyright notice on Your software product in which
20 | the Sample Code is embedded; and
21 | 3. to indemnify, hold harmless, and defend Us and Our suppliers from and
22 | against any claims or lawsuits, including attorneys' fees, that arise
23 | or result from the use or distribution of the Sample Code.
24 |
25 |
26 | ALL CODE MUST BE TESTED BY ANY RECIPIENTS AND SHOULD NOT BE RUN IN A PRODUCTION ENVIRONMENT WITHOUT MODIFICATION BY THE RECIPIENT.
27 |
--------------------------------------------------------------------------------
/Registry/Search-RegistrySubtreeByProperty.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability or fitness for a particular purpose.
3 | This mail message assumes that you are familiar with the programming language that is being demonstrated and the tools that are used to create and debug procedures.
4 | #requires -version 2.0
5 |
6 | .DESCRIPTION
7 | .NOTES
8 | Author: Mark Warneke
9 | Created: 12-04-17
10 | .LINK
11 | #>
12 |
13 | [CmdletBinding()]
14 | Param(
15 | [
16 | Parameter(
17 | Mandatory=$True
18 | )
19 | ]
20 | [string] $Path,
21 |
22 | [
23 | Parameter(
24 | Mandatory=$True
25 | )
26 | ]
27 | [string] $SearchItemPropertyKeyName
28 | )
29 |
30 | # [string] $Path = "HKLM:\SYSTEM\ControlSet001\services\Dynamics Server\"
31 | # [string] $Path = "HKLM:\SYSTEM\ControlSet001\Services\Dhcp"
32 |
33 | # $SearchItemPropertyKeyName = "RegLocation"
34 | # $SearchItemPropertyKeyValue = "SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\?\Dhcpv6DNSServers"
35 |
36 | $Items = Get-ChildItem -Path $Path -Recurse
37 |
38 | foreach ($item in $Items) {
39 |
40 | $Propertys = Get-ItemProperty $item.PSPath
41 |
42 | foreach ($property in $Propertys) {
43 | if ( $property.$SearchItemPropertyKeyName ) {
44 | $item
45 | $property
46 | Write-Host
47 | }
48 | }
49 |
50 | }
51 |
52 |
--------------------------------------------------------------------------------
/Hyper-V/New-Image.ps1:
--------------------------------------------------------------------------------
1 | # This script creates a new Hyper-V machine with hard drive, memory & network resources configured.
2 |
3 | # Variables
4 | $SRV1 = Read-Host "Enter the Virtual Machine name (Press [Enter] to choose Server01): "
5 | if ($SRV1 -eq ""){$SRV1="Server01"} ; if ($SRV1 -eq $NULL){$SRV1="Server01"}
6 |
7 | $SRAM = Read-Host "Enter the size of the Virtual Machine Memory (Press [Enter] to choose 512MB): "
8 | if ($SRAM -eq ""){$SRAM=512MB} ; if ($SRAM -eq $NULL){$SRAM=512MB}
9 |
10 | $SRV1VHD = Read-Host "Enter the size of the Virtual Machine Hard Drive (Press [Enter] to choose 40GB): "
11 | if ($SRV1VHD -eq ""){$SRV1VHD=40GB} ; if ($SRV1VHD -eq $NULL){$SRV1VHD=40GB}
12 |
13 | $VMLOC = Read-Host "Enter the location of the Virtual Machine file (Press [Enter] to choose C:\HyperV): "
14 | if ($VMLOC -eq ""){$VMLOC="C:\HyperV"} ; if ($VMLOC -eq $NULL){$VMLOC="C:\HyperV"}
15 |
16 | $Network1 = Read-Host "Enter the name of the Virtual Machine Network (Press [Enter] to choose Network1): "
17 | if ($Network1 -eq ""){$Network1="Network1"} ; if ($Network1 -eq $NULL){$Network1="Network1"}
18 |
19 | # Configure Hyper-V Virtual Network
20 | remove-vmswitch $Network1 -force -erroractionsilentlycontinue
21 | new-vmprivateswitch $Network1
22 |
23 | # Create Virtual Machines
24 | MD $VMLoc -erroractionsilentlycontinue
25 | new-vm $SRV1 -path $VMLoc
26 | new-vhd -vhdpaths $VMLoc\$SRV1 -size $SRV1VHD
27 | add-vmdisk -vm $SRV1 -controllerid 0 -lun 0 -path $VMLoc\$SRV1
28 | get-vm $SRV1 | add-vmdrive -controllerid 1 -lun 0 -dvd
29 | get-vm $SRV1 | set-vmmemory -memory $SRAM
30 | get-vm $SRV1 | add-vmnic -virtualswitch $Network1
--------------------------------------------------------------------------------
/Hyper-V/Create-HyperVClienServer.ps1:
--------------------------------------------------------------------------------
1 | # This script configures the Hyper-V machines used for the 50331 Course.
2 | # PowerShell 3.0 and Windows Server 2012 or Windows 8 Pro are required to perform this setup.
3 | # The C:\ Drive should have at least 200GB of free space available.
4 | # All the files on the 50331 Student CD should be copied to C:\Labfiles before performing this setup.
5 |
6 | # Variables
7 | $CLI1 = "50331-CUSTOM-CLI" # Name of VM running Client Operating System
8 | $SRV1 = "50331-CUSTOM-SRV" # Name of VM running Server Operating System
9 | $CRAM = 2GB # RAM assigned to Client Operating System
10 | $SRAM = 1GB # RAM assigned to Server Operating System
11 | $CLI1VHD = 80GB # Size of Hard-Drive for Client Operating System
12 | $SRV1VHD = 40GB # Size of Hard-Drive for Server Operating System
13 | $VMLOC = "C:\HyperV" # Location of the VM and VHDX files
14 | $NetworkSwitch1 = "PrivateSwitch1" # Name of the Network Switch
15 | $W7ISO = "C:\Labfiles\Windows7.iso" # Windows 7 ISO
16 | $W7VFD = "C:\Labfiles\Windows7.vfd" # Windows 7 Virtual Floppy Disk with autounattend.xml file
17 | $WSISO = "C:\Labfiles\W2K8R2.iso" # Windows Server 2008 ISO
18 | $WSVFD = "C:\Labfiles\W2K8R2.vfd" # Windows Server 2008 Virtual Floppy Disk with autounattend.xml file
19 |
20 | # Create VM Folder and Network Switch
21 | MD $VMLOC -ErrorAction SilentlyContinue
22 | $TestSwitch = Get-VMSwitch -Name $NetworkSwitch1 -ErrorAction SilentlyContinue; if ($TestSwitch.Count -EQ 0){New-VMSwitch -Name $NetworkSwitch1 -SwitchType Private}
23 |
24 | # Create Virtual Machines
25 | New-VM -Name $CLI1 -Path $VMLOC -MemoryStartupBytes $CRAM -NewVHDPath $VMLOC\$CLI1.vhdx -NewVHDSizeBytes $CLI1VHD -SwitchName $NetworkSwitch1
26 | New-VM -Name $SRV1 -Path $VMLOC -MemoryStartupBytes $SRAM -NewVHDPath $VMLOC\$SRV1.vhdx -NewVHDSizeBytes $SRV1VHD -SwitchName $NetworkSwitch1
27 |
28 | # Configure Virtual Machines
29 | Set-VMDvdDrive -VMName $CLI1 -Path $W7ISO
30 | Set-VMDvdDrive -VMName $SRV1 -Path $WSISO
31 | Set-VMFloppyDiskDrive -VMName $CLI1 -Path $W7VFD
32 | Set-VMFloppyDiskDrive -VMName $SRV1 -Path $WSVFD
33 | Start-VM $SRV1
34 | Start-VM $CLI1
--------------------------------------------------------------------------------
/Remote/Collect-Perf.ps1:
--------------------------------------------------------------------------------
1 | # http://sqlblog.com/blogs/aaron_bertrand/archive/2011/01/31/how-i-use-powershell-to-collect-performance-counter-data.aspx
2 |
3 | param([string]$server, [string]$role, [string]$test, [int]$delay, [int]$count, [string]$path)
4 |
5 | function CollectPerf {
6 | param(
7 | [string]$server,
8 | [string]$role,
9 | [string]$test,
10 | [int]$delay,
11 | [int]$count,
12 | [string]$path
13 | )
14 |
15 | if ($role -eq "app server")
16 | {
17 | $counters = @("\Processor(_Total)\% Processor Time",
18 | "\System\Processor Queue Length"
19 | # -- other counters
20 | )
21 | }
22 |
23 | if ($role -eq "db server")
24 | {
25 | $counters = @("\PhysicalDisk(_Total)\Avg. Disk sec/Read",
26 | "\SQLServer:SQL Statistics\Batch Requests/sec"
27 | # -- other counters
28 | )
29 | }
30 |
31 | # other roles...
32 |
33 | $sequence = 1;
34 |
35 | $metrics = Get-Counter -ComputerName $server -Counter $counters -SampleInterval $delay -MaxSamples $count
36 |
37 | foreach($metric in $metrics)
38 | {
39 | $obj = $metric.CounterSamples | Select-Object -Property Path, CookedValue, Timestamp;
40 | # add these columns as data
41 | $obj | Add-Member -MemberType NoteProperty -Name Sequence -Value $sequence -Force;
42 | $obj | Add-Member -MemberType NoteProperty -Name LoadTest -Value $test -Force;
43 | $obj | Add-Member -MemberType NoteProperty -Name Computer -Value $server -Force;
44 | # export with unique file name
45 | $obj | Export-Csv -Path "$path$server.$test.$sequence.csv" -NoTypeInformation;
46 | $sequence += 1;
47 | }
48 | }
49 | CollectPerf -server $server -role $role -test $test -delay $delay -count $count -path $path
--------------------------------------------------------------------------------
/Remote/New-DataCollectorSet.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .SYNOPSIS
3 | Create a New Perfmon Data Collector Set from an XML input
4 | .DESCRIPTION
5 | Create a New Perfmon Data Collector Set from an XML input
6 | Use PowerShell remoting to create these on a remote server.
7 | Remoting must be enabled on target servers
8 | .NOTES
9 | Authors: Jonathan Medd
10 | .PARAMETER CSVFilePath
11 | Path of CSV file to import
12 | .PARAMETER XMLFilePath
13 | Path of XML file to import
14 | .PARAMETER DataCollectorName
15 | Name of new Data Collector. This should match the name in the XML file
16 | .EXAMPLE
17 | New-DataCollectorSet -CSVFilePath C:\Scripts\Servers.csv -XMLFilePath C:\Scripts\PerfmonTemplate.xml -DataCollectorName CPUIssue
18 | #>
19 | param (
20 | [parameter(Mandatory=$True,HelpMessage='Path of CSV file to import')]
21 | $CSVFilePath
22 | ,
23 | [parameter(Mandatory=$True,HelpMessage='Path of XML file to import')]
24 | $XMLFilePath
25 | ,
26 | [parameter(Mandatory=$True,HelpMessage='Name of new Data Collector')]
27 | $DataCollectorName
28 | )
29 |
30 | # Test for existence of supplied CSV and XML files
31 | if (Test-Path $CSVFilePath){
32 | }
33 | else{
34 | Write-Host "Path to CSV file is invalid, exiting script"
35 | Exit
36 | }
37 | if (Test-Path $XMLFilePath){
38 | }
39 | else{
40 | Write-Host "Path to XML file is invalid, exiting script"
41 | Exit
42 | }
43 |
44 | # Generate list of servers to create Perfmon Data Collector Sets on
45 | $servers = Get-Content $CSVFilePath
46 |
47 | foreach ($server in $servers){
48 |
49 | Write-Host "Creating Data Collector Set on $Server"
50 |
51 | # Test if the folder C:\temp exists on the target server
52 | if (Test-Path "\\$server\c$\Temp"){
53 |
54 | # Copy the XML file to the target server
55 | Copy-Item $XMLFilePath "\\$server\c$\Temp"
56 |
57 | # Use PowerShell Remoting to execute script block on target server
58 | Invoke-Command -ComputerName $server -ArgumentList $DataCollectorName -ScriptBlock {param($DataCollectorName)
59 |
60 | # Create a new DataCollectorSet COM object, read in the XML file,
61 | # use that to set the XML setting, create the DataCollectorSet,
62 | # start it.
63 | $datacollectorset = New-Object -COM Pla.DataCollectorSet
64 | $xml = Get-Content C:\temp\PerfmonTemplate.xml
65 | $datacollectorset.SetXml($xml)
66 | $datacollectorset.Commit("$DataCollectorName" , $null , 0x0003) | Out-Null
67 | $datacollectorset.start($false)
68 | }
69 |
70 | # Remove the XML file from the target server
71 | Remove-Item "\\$server\c$\Temp\PerfmonTemplate.xml"
72 | }
73 | else{
74 | Write-Host "Target Server does not contain the folder C:\Temp"
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Server/Set-UserFlag.ps1:
--------------------------------------------------------------------------------
1 | # http://msdn.microsoft.com/en-us/library/aa772300(VS.85).aspx
2 | $ADS_UF_SCRIPT = 1 # 0x1
3 | $ADS_UF_ACCOUNTDISABLE = 2 # 0x2
4 | $ADS_UF_HOMEDIR_REQUIRED = 8 # 0x8
5 | $ADS_UF_LOCKOUT = 16 # 0x10
6 | $ADS_UF_PASSWD_NOTREQD = 32 # 0x20
7 | $ADS_UF_PASSWD_CANT_CHANGE = 64 # 0x40
8 | $ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128 # 0x80
9 | $ADS_UF_TEMP_DUPLICATE_ACCOUNT = 256 # 0x100
10 | $ADS_UF_NORMAL_ACCOUNT = 512 # 0x200
11 | $ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 2048 # 0x800
12 | $ADS_UF_WORKSTATION_TRUST_ACCOUNT = 4096 # 0x1000
13 | $ADS_UF_SERVER_TRUST_ACCOUNT = 8192 # 0x2000
14 | $ADS_UF_DONT_EXPIRE_PASSWD = 65536 # 0x10000
15 | $ADS_UF_MNS_LOGON_ACCOUNT = 131072 # 0x20000
16 | $ADS_UF_SMARTCARD_REQUIRED = 262144 # 0x40000
17 | $ADS_UF_TRUSTED_FOR_DELEGATION = 524288 # 0x80000
18 | $ADS_UF_NOT_DELEGATED = 1048576 # 0x100000
19 | $ADS_UF_USE_DES_KEY_ONLY = 2097152 # 0x200000
20 | $ADS_UF_DONT_REQUIRE_PREAUTH = 4194304 # 0x400000
21 | $ADS_UF_PASSWORD_EXPIRED = 8388608 # 0x800000
22 | $ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 16777216 # 0x1000000
23 |
24 | Function AddUserFlag()
25 | {
26 | $userName = $args[0]
27 | $flag = $args[1]
28 | $u = [adsi]"WinNT://$env:computername/$userName,user"
29 | $u.invokeSet("userFlags", ($u.userFlags[0] -BOR $flag))
30 | $u.commitChanges()
31 | }
32 |
33 | Function RemoveUserFlag()
34 | {
35 | $userName = $args[0]
36 | $flag = $args[1]
37 | $u = [adsi]"WinNT://$env:computername/$userName,user"
38 | if ($u.UserFlags[0] -BAND $flag)
39 | {
40 | $u.invokeSet("userFlags", ($u.userFlags[0] -BXOR $flag))
41 | $u.commitChanges()
42 | }
43 | }
44 |
45 | $computer = [ADSI]"WinNT://$env:computername,computer"
46 | $Users = $computer.psbase.Children |
47 | Where-Object {$_.psbase.schemaclassname -eq 'user'}
48 | foreach ($user in $Users.psbase.syncroot)
49 | {
50 | If ($user.name -eq "Administrator")
51 | {
52 | AddUserFlag $user.name $ADS_UF_DONT_EXPIRE_PASSWD
53 | }
54 | Else
55 | {
56 | RemoveUserFlag $user.name $ADS_UF_DONT_EXPIRE_PASSWD
57 | }
58 | }
--------------------------------------------------------------------------------
/Others/Create-BasicForm.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .Synopsis
3 | Basic form created with powershell
4 |
5 | .Description
6 | Creates a simple form from PowerShell to select entries
7 |
8 | .Parameter parameter1
9 | parameterDescription
10 |
11 | .Example
12 | eampleDesciption
13 |
14 | #>
15 |
16 |
17 | <#
18 | DISCLAIMER:
19 |
20 | Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability or fitness for a particular purpose.
21 | This mail message assumes that you are familiar with the programming language that is being demonstrated and the tools that are used to create and debug procedures.
22 | #requires -version 2.0
23 |
24 | Author: Mark Warneke
25 | Created: 14-Apr-17
26 | #>
27 |
28 | Add-Type -AssemblyName System.Windows.Forms
29 | Add-Type -AssemblyName System.Drawing
30 |
31 | $form = New-Object System.Windows.Forms.Form
32 | $form.Text = "Data Entry Form"
33 | $form.Size = New-Object System.Drawing.Size(300,200)
34 | $form.StartPosition = "CenterScreen"
35 |
36 | $OKButton = New-Object System.Windows.Forms.Button
37 | $OKButton.Location = New-Object System.Drawing.Point(75,120)
38 | $OKButton.Size = New-Object System.Drawing.Size(75,23)
39 | $OKButton.Text = "OK"
40 | $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
41 | $form.AcceptButton = $OKButton
42 | $form.Controls.Add($OKButton)
43 |
44 | $CancelButton = New-Object System.Windows.Forms.Button
45 | $CancelButton.Location = New-Object System.Drawing.Point(150,120)
46 | $CancelButton.Size = New-Object System.Drawing.Size(75,23)
47 | $CancelButton.Text = "Cancel"
48 | $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
49 | $form.CancelButton = $CancelButton
50 | $form.Controls.Add($CancelButton)
51 |
52 | $label = New-Object System.Windows.Forms.Label
53 | $label.Location = New-Object System.Drawing.Point(10,20)
54 | $label.Size = New-Object System.Drawing.Size(280,20)
55 | $label.Text = "Please make a selection from the list below:"
56 | $form.Controls.Add($label)
57 |
58 | $listBox = New-Object System.Windows.Forms.Listbox
59 | $listBox.Location = New-Object System.Drawing.Point(10,40)
60 | $listBox.Size = New-Object System.Drawing.Size(260,20)
61 |
62 | $listBox.SelectionMode = "MultiExtended"
63 |
64 | [void] $listBox.Items.Add("Item 1")
65 | [void] $listBox.Items.Add("Item 2")
66 | [void] $listBox.Items.Add("Item 3")
67 | [void] $listBox.Items.Add("Item 4")
68 | [void] $listBox.Items.Add("Item 5")
69 |
70 | $listBox.Height = 70
71 | $form.Controls.Add($listBox)
72 | $form.Topmost = $True
73 |
74 | $result = $form.ShowDialog()
75 |
76 | if ($result -eq [System.Windows.Forms.DialogResult]::OK)
77 | {
78 | $x = $listBox.SelectedItems
79 | $x
80 | }
--------------------------------------------------------------------------------
/Others/Set-PowerConfigurationActive.ps1:
--------------------------------------------------------------------------------
1 | #| = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = |
2 | #|{>/-------------------------------------------------------------\<}|
3 | #|: | Author: Aman Dhally
4 | #| :| Email: amandhally@gmail.com
5 | #|: | Purpose:
6 | #| :| Check the PowerScheme on the Laptop and Assign the Desired One
7 | #|: |
8 | #|: | Date: 09-11-2011
9 | #| :| /^(o.o)^\
10 | #|{>\-------------------------------------------------------------/<}|
11 | #| = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = |
12 | #+-------------------------------------------------------------------+#
13 | # Powercfg - L # to get the Available list of all Power Settings schemes
14 | # powercfg -L#
15 | #
16 | #Existing Power Schemes (* Active)
17 | #-----------------------------------
18 | #Power Scheme GUID: 1ca6081e-7f76-46f8-b8e5-92a6bd9800cd (Maximum Battery
19 | #Power Scheme GUID: 2ae0e187-676e-4db0-a121-3b7ddeb3c420 (Power Source Opt
20 | #Power Scheme GUID: 37aa8291-02f6-4f6c-a377-6047bba97761 (Timers off (Pres
21 | #Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)
22 | #Power Scheme GUID: 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c (High performance
23 | #Power Scheme GUID: a1841308-3541-4fab-bc81-f71556f20b4a (Power saver)
24 | #Power Scheme GUID: a666c91e-9613-4d84-a48e-2e4b7a016431 (Maximum Performa
25 | #Power Scheme GUID: de7ef2ae-119c-458b-a5a3-997c2221e76e (Energy Star)
26 | #Power Scheme GUID: e11a5899-9d8e-4ded-8740-628976fc3e63 (Video Playback)
27 | #
28 | #
29 | #
30 |
31 | ##### Variables # # # # # #
32 |
33 |
34 | ## I want to Use Energy Start as Deault PowerScheme on All Laptops #
35 |
36 | $x = 'de7ef2ae-119c-458b-a5a3-997c2221e76e'
37 |
38 | # Lets Check what is our Current Active "Power Scheme" and put it on a Variable
39 |
40 | $currScheme = POWERCFG -GETACTIVESCHEME
41 |
42 | # Put $CurrScheme in a variable and Spilt is so that we can get the GUID of Active "Power Scheme"
43 |
44 | $y = $currScheme.Split()
45 |
46 | #############################
47 | ### Script Starts Here ######
48 | #############################
49 |
50 | # $y[3] is GUID of Active "Power Scheme"
51 | if ($y[3] -eq $x) {
52 |
53 | write-Host -ForegroundColor yellow "You Have correct Settings, Nothing to Do!!! "
54 |
55 | } else {
56 |
57 | Write-Warning "You Have Wrong Power Scheme Set, let me fix it for you"
58 |
59 | PowerCfg -SetActive $x
60 |
61 | write-Host -ForegroundColor Green "PowerScheme Sucessfully Applied"
62 |
63 | }
64 |
65 |
66 | ##### End of Script # # # #
67 | #### Its Tested on Windows 7 Only ##########
--------------------------------------------------------------------------------
/Others/Set-Wallpaper.ps1:
--------------------------------------------------------------------------------
1 | #requires -version 2.0
2 | ## Set-Wallpaper - set your windows desktop wallpaper
3 | ###################################################################################################
4 | ## Usage:
5 | ## Set-Wallpaper "C:\Users\Joel\Pictures\Wallpaper\Dual Monitor\mandolux-tiger.jpg" "Tile"
6 | ## ls *.jpg | get-random | Set-Wallpaper
7 | ## ls *.jpg | get-random | Set-Wallpaper -Style "Stretch"
8 | ###################################################################################################
9 | ## History:
10 | ## v0.5 First release (on #PowerShell@irc.freenode.net)
11 | ## v1.0 Public release (http://www.poshcode.org/488)
12 | ## - Added Style: Tile|Center|Stretch
13 | ## v1.1 This Release
14 | ## - Added "NoChange" style to just use the style setting already set
15 | ## - Made the Style parameter to the cmdlet optional
16 | ###################################################################################################
17 |
18 | add-type @"
19 | using System;
20 | using System.Runtime.InteropServices;
21 | using Microsoft.Win32;
22 | namespace Wallpaper
23 | {
24 | public enum Style : int
25 | {
26 | Tile, Center, Stretch, NoChange
27 | }
28 |
29 |
30 | public class Setter {
31 | public const int SetDesktopWallpaper = 20;
32 | public const int UpdateIniFile = 0x01;
33 | public const int SendWinIniChange = 0x02;
34 |
35 | [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
36 | private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
37 |
38 | public static void SetWallpaper ( string path, Wallpaper.Style style ) {
39 | SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
40 |
41 | RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
42 | switch( style )
43 | {
44 | case Style.Stretch :
45 | key.SetValue(@"WallpaperStyle", "2") ;
46 | key.SetValue(@"TileWallpaper", "0") ;
47 | break;
48 | case Style.Center :
49 | key.SetValue(@"WallpaperStyle", "1") ;
50 | key.SetValue(@"TileWallpaper", "0") ;
51 | break;
52 | case Style.Tile :
53 | key.SetValue(@"WallpaperStyle", "1") ;
54 | key.SetValue(@"TileWallpaper", "1") ;
55 | break;
56 | case Style.NoChange :
57 | break;
58 | }
59 | key.Close();
60 | }
61 | }
62 | }
63 | "@
64 |
65 | cmdlet Set-Wallpaper {
66 | Param(
67 | [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
68 | [Alias("FullName")]
69 | [string]
70 | $Path
71 | ,
72 | [Parameter(Position=1, Mandatory=$false)]
73 | [Wallpaper.Style]
74 | $Style = "NoChange"
75 | )
76 | [Wallpaper.Setter]::SetWallpaper( (Convert-Path $Path), $Style )
77 | }
--------------------------------------------------------------------------------
/Others/Send-EmailTest.ps1:
--------------------------------------------------------------------------------
1 | #REQUIRES -Version 4.0
2 | #REQUIRES -Modules MyModule1,MyModule2
3 | #REQUIRES -RunAsAdministrator
4 |
5 | <#
6 | DISCLAIMER:
7 |
8 | This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment.
9 |
10 | THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED AS IS
11 | WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
12 | TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
13 |
14 | We grant You a nonexclusive, royalty-free right to use and modify the Sample Code and
15 | to reproduce and distribute the object code form of the Sample Code,
16 | provided that You agree:
17 | (i) to not use Our name, logo, or trademarks to market Your software
18 | product in which the Sample Code is embedded;
19 | (ii) include a valid copyright notice on Your software product in which
20 | the Sample Code is embedded; and
21 | (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and
22 | against any claims or lawsuits, including attorneys' fees, that arise
23 | or result from the use or distribution of the Sample Code.
24 |
25 | Please note: None of the conditions outlined in the disclaimer above will supersede terms and conditions contained within the Premier Customer Services Description.
26 |
27 | ALL CODE MUST BE TESTED BY ANY RECIPIENTS AND SHOULD NOT BE RUN IN A PRODUCTION ENVIRONMENT WITHOUT MODIFICATION BY THE RECIPIENT.
28 |
29 | Author: Mark Warneke
30 | Created:
31 |
32 |
33 | HELP
34 |
35 | .SYNOPSIS
36 | Send an email to an recipient using ssl
37 |
38 | .DESCRIPTION
39 | Send an email from an certain email adress to a recepient, provided as a parameter with a certain smtp
40 |
41 | .PARAMETER
42 | $To
43 | Email Recepient
44 |
45 | .PARAMETER
46 | $To
47 | Email Recepient
48 |
49 | .EXAMPLE
50 | Send-Email
51 | #>
52 |
53 |
54 | <#
55 | Brief descirption of the fuction.
56 | #>
57 | function Send-Email {
58 | [CmdletBinding()]
59 | [OutputType([int])]
60 | param(
61 | [Parameter(Mandatory=$true)]
62 | [string]
63 | $To,
64 | [Parameter(Mandatory=$true)]
65 | [string]
66 | $Body,
67 | [string]
68 | $Subject = "Notification",
69 | [string]
70 | $EmailFrom = "from@mail.com",
71 | [string]
72 | $SMTPServer = "YOUR.SMTP.MAIL.SERVER"
73 | )
74 |
75 | begin {
76 | }
77 |
78 | process {
79 | try {
80 | $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
81 | $SMTPClient.EnableSsl = $true
82 | $SMTPClient.Credentials = Get-Credential $EmailFrom
83 | $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
84 | } catch {
85 | Write-Error "sending mail from $From to $To failed"
86 | }
87 |
88 | }
89 |
90 | end {
91 | }
92 | }
93 |
94 | # export-modulemember -function Send-Email
--------------------------------------------------------------------------------
/Hyper-V/Create-HyperV.ps1:
--------------------------------------------------------------------------------
1 | #REQUIRES -Version 3.0
2 |
3 | <#
4 | DISCLAIMER:
5 |
6 | This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment.
7 |
8 | THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED AS IS
9 | WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
10 | TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
11 |
12 | We grant You a nonexclusive, royalty-free right to use and modify the Sample Code and
13 | to reproduce and distribute the object code form of the Sample Code,
14 | provided that You agree:
15 | (i) to not use Our name, logo, or trademarks to market Your software
16 | product in which the Sample Code is embedded;
17 | (ii) include a valid copyright notice on Your software product in which
18 | the Sample Code is embedded; and
19 | (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and
20 | against any claims or lawsuits, including attorneys' fees, that arise
21 | or result from the use or distribution of the Sample Code.
22 |
23 | Please note: None of the conditions outlined in the disclaimer above will supersede terms and conditions contained within the Premier Customer Services Description.
24 |
25 | ALL CODE MUST BE TESTED BY ANY RECIPIENTS AND SHOULD NOT BE RUN IN A PRODUCTION ENVIRONMENT WITHOUT MODIFICATION BY THE RECIPIENT.
26 |
27 | Author: Mark Warneke
28 | Created: <05-19-2017>
29 |
30 |
31 | HELP
32 |
33 | .SYNOPSIS
34 | Creates a new Hyper-V Virtual Machine on the default location
35 |
36 | .DESCRIPTION
37 | Creates a new Hyper-V Virtual Machine on the default location with the mandatroy parameters
38 | #>
39 |
40 | function Create-HyperV {
41 | [CmdletBinding()]
42 | param(
43 | [Parameter()]
44 | [string] $VmName = "NewVirtualMachine",
45 | $VmRam = 4GB,
46 | $VmVhdSize = 40GB,
47 | [string] $VmPath = "C:\VMs",
48 | [string] $VmNetworkSwitch = "Internal Virtual Switch",
49 | [string] $IsoFile = "C:\VMs\en_windows_server_2016_x64_dvd_9718492.iso"
50 |
51 | )
52 |
53 | begin {
54 |
55 | if (-Not (Test-Path -Path $VmPath)) {
56 | Write-Verbose -Message "Create $VmPath directory"
57 | mkdir $VmPath -ErrorAction SilentlyContinue
58 | }
59 |
60 | if (-Not (Test-Path -Path $IsoFile)) {
61 | Write-Error -Message "Iso-File not found"
62 | }
63 | }
64 |
65 | process {
66 |
67 | $Switch = Get-VMSwitch -Name $VmNetworkSwitch -ErrorAction SilentlyContinue
68 |
69 | if ($Switch.Count -EQ 0){
70 | Write-Verbose -Message "Create Private $VmNetworkSwitch VMSwitch"
71 | New-VMSwitch -Name $VmNetworkSwitch -SwitchType Private
72 | }
73 |
74 | Write-Verbose -Message "Create new VM $VmName in $VmPath with $VmRam RAM $VmVhdSize GB"
75 | New-VM -Name $VmName -Path $VmPath -MemoryStartupBytes $VmRam -NewVHDPath $VmPath\$VmName.vhdx -NewVHDSizeBytes $VmVhdSize -SwitchName $VmNetworkSwitch
76 |
77 | Write-Verbose -Message "Configure VM $VmName drive $IsoFile"
78 | Set-VMDvdDrive -VMName $VmName -Path $IsoFile
79 |
80 | Start-VM $SRV1
81 | }
82 |
83 | end {
84 | }
85 | }
86 |
87 | export-modulemember -function Create-HyperV
88 |
89 |
--------------------------------------------------------------------------------
/Others/RenameAndMoveChildItemFileToParentDir.ps1:
--------------------------------------------------------------------------------
1 | #REQUIRES -Version 4.0
2 | #REQUIRES -Modules MyModule1,MyModule2
3 | #REQUIRES -RunAsAdministrator
4 |
5 | <#
6 | DISCLAIMER:
7 |
8 | This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment.
9 |
10 | THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED AS IS
11 | WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
12 | TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
13 |
14 | We grant You a nonexclusive, royalty-free right to use and modify the Sample Code and
15 | to reproduce and distribute the object code form of the Sample Code,
16 | provided that You agree:
17 | (i) to not use Our name, logo, or trademarks to market Your software
18 | product in which the Sample Code is embedded;
19 | (ii) include a valid copyright notice on Your software product in which
20 | the Sample Code is embedded; and
21 | (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and
22 | against any claims or lawsuits, including attorneys' fees, that arise
23 | or result from the use or distribution of the Sample Code.
24 |
25 | Please note: None of the conditions outlined in the disclaimer above will supersede terms and conditions contained within the Premier Customer Services Description.
26 |
27 | ALL CODE MUST BE TESTED BY ANY RECIPIENTS AND SHOULD NOT BE RUN IN A PRODUCTION ENVIRONMENT WITHOUT MODIFICATION BY THE RECIPIENT.
28 |
29 | Author: Mark Warneke
30 | Created: <06-07-2017>
31 |
32 |
33 | HELP
34 |
35 | .SYNOPSIS
36 | Renames and moves the file (!) inside a collection of folders to the parent folder and naming them as the folder they are contained.
37 |
38 | .DESCRIPTION
39 | Gets alls the folders inside a specified path. Enumerates them and looks for files inside the folder.
40 | It renames the files inside the folder to the folders name and moves it to the parent folder.
41 | deletes the parent folder of the file.
42 |
43 | #>
44 |
45 |
46 | <#
47 | Brief descirption of the fuction.
48 | #>
49 | function RenameMove-FilesInFolder {
50 | [CmdletBinding()]
51 | [OutputType([int])]
52 | param(
53 | [Parameter(Mandatory = $true)]
54 | [string] $path,
55 | [bool] $test = $false
56 | )
57 |
58 | begin {
59 |
60 | $oldverbose = $VerbosePreference
61 |
62 | if ($test) {
63 | $p = "1234"
64 | $f = "test.txt"
65 |
66 | mkdir $p
67 | mv ".\$p.txt" ".\$p\$f"
68 |
69 | $VerbosePreference = "continue"
70 | }
71 | }
72 |
73 | process {
74 |
75 | $dirs = get-childitem -dir -Path $path
76 |
77 | foreach ($dir in $dirs) {
78 | write-verbose ("In directory $directoryName")
79 | $directoryName = $dir.Name
80 | $directoryParentDir = $dir.PSParentPath
81 | $files = Get-ChildItem $name
82 |
83 | if (-Not $files.Length) {
84 | Write-Error ("More than one file in $dir found - abroat")
85 | exit
86 | }
87 |
88 | foreach ($file in $files) {
89 |
90 | write-verbose ("Got file $file")
91 | $fileName = $file.Name
92 | $fileDirectory = $file.DirectoryName
93 |
94 | try {
95 | write-verbose ("Moving $file from $fileDirectory to $directoryParentDir with name $directoryName.txt")
96 | move-item "$fileDirectory\$fileName" "$directoryParentDir\$directoryName.txt"
97 |
98 | write-verbose ("Deleting $file parent directory $dir")
99 | remove-item $dir
100 |
101 | Get-ChildItem
102 | } catch {
103 | write-error ("Unable to move-item $file to $dir")
104 | }
105 |
106 | }
107 | }
108 |
109 | $VerbosePreference = $oldverbose
110 | }
111 |
112 | end {
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/Others/Get-ServiceStartTime.ps1:
--------------------------------------------------------------------------------
1 | #REQUIRES -Version 2.0
2 |
3 | <#
4 | DISCLAIMER:
5 |
6 | This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment.
7 |
8 | THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED AS IS
9 | WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
10 | TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
11 |
12 | We grant You a nonexclusive, royalty-free right to use and modify the Sample Code and
13 | to reproduce and distribute the object code form of the Sample Code,
14 | provided that You agree:
15 | (i) to not use Our name, logo, or trademarks to market Your software
16 | product in which the Sample Code is embedded;
17 | (ii) include a valid copyright notice on Your software product in which
18 | the Sample Code is embedded; and
19 | (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and
20 | against any claims or lawsuits, including attorneys' fees, that arise
21 | or result from the use or distribution of the Sample Code.
22 |
23 | Please note: None of the conditions outlined in the disclaimer above will supersede terms and conditions contained within the Premier Customer Services Description.
24 |
25 | ALL CODE MUST BE TESTED BY ANY RECIPIENTS AND SHOULD NOT BE RUN IN A PRODUCTION ENVIRONMENT WITHOUT MODIFICATION BY THE RECIPIENT.
26 |
27 | Author: Mark Warneke
28 | Created: 05-30-2017
29 |
30 |
31 | HELP
32 |
33 | .SYNOPSIS
34 | Funciton to get the start time of the service through the wmi api
35 |
36 | .DESCRIPTION
37 | Funciton to get the start time of the service through the wmi api
38 | Gets the service by name and gets the actual process startet.
39 |
40 | .PARAMETER
41 | ComputerName
42 |
43 | .PARAMETER
44 | Name ServiceName
45 |
46 |
47 | .EXAMPLE
48 | C:\PS> .\Get-ServiceStartTime.ps1 -ComputerName “mytestpc1” -Name spooler
49 |
50 | .EXAMPLE
51 | C:\PS> .\Get-ServiceStartTime.ps1 -ComputerName “mytestpc1”, “mytestpc2” -Name spooler
52 |
53 | .Source
54 | http://techibee.com/powershell/powershell-query-windows-service-start-time/1336
55 | #>
56 |
57 |
58 | <#
59 | Funciton to get the start time of the service through the wmi api
60 | Gets the service by name and gets the actual process startet.
61 | #>
62 |
63 | [cmdletbinding()]
64 |
65 | param (
66 | [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
67 | [string[]]$ComputerName = $env:computername,
68 |
69 | [ValidateNotNullOrEmpty()]
70 | [parameter(Mandatory = $true)]
71 | [Alias("ServiceName")]
72 | [string]$Name
73 |
74 | )
75 |
76 | begin {}
77 |
78 | Process {
79 |
80 | foreach ($Computer in $ComputerName) {
81 | if (Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
82 | Write-Verbose "$Computer is online"
83 |
84 | Write-Verbose "Query ServiceName $Name fom $Computer"
85 | $Service = Get-WmiObject -Class Win32_Service -ComputerName $Computer -Filter "Name='$Name'" -ea 0
86 |
87 | if ($Service) {
88 |
89 | Write-Verbose "Service $Name found, obtain PID"
90 | $ServicePID = $Service.ProcessID
91 |
92 | Write-Verbose "Query process information $ServicePID from ServiceName $Name fom $Computer"
93 | $ProcessInfo = Get-WmiObject -Class Win32_Process -ComputerName $Computer -Filter "ProcessID='$ServicePID'" -ea 0
94 |
95 | Write-Verbose "Create return object"
96 | $OutputObj = New-Object -Type PSObject
97 | $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
98 | $OutputObj | Add-Member -MemberType NoteProperty -Name Name -Value $Name
99 | $OutputObj | Add-Member -MemberType NoteProperty -Name DisplayName -Value $Service.DisplayName
100 | $OutputObj | Add-Member -MemberType NoteProperty -Name StartTime -Value $($Service.ConvertToDateTime($ProcessInfo.CreationDate))
101 | $OutputObj
102 |
103 | }
104 | else {
105 | write-verbose "Service `($Name`) not found on $Computer"
106 | }
107 | }
108 | else {
109 | write-Verbose "$Computer is offline"
110 | }
111 | }
112 |
113 | }
114 |
115 | end {}
--------------------------------------------------------------------------------
/Registry/search-registry.ps1:
--------------------------------------------------------------------------------
1 | function Search-Registry {
2 | <#
3 | .SYNOPSIS
4 | Searches registry key names, value names, and value data (limited).
5 |
6 | .DESCRIPTION
7 | This function can search registry key names, value names, and value data (in a limited fashion). It outputs custom objects that contain the key and the first match type (KeyName, ValueName, or ValueData).
8 |
9 | .EXAMPLE
10 | Search-Registry -Path HKLM:\SYSTEM\CurrentControlSet\Services\* -SearchRegex "svchost" -ValueData
11 |
12 | .EXAMPLE
13 | Search-Registry -Path HKLM:\SOFTWARE\Microsoft -Recurse -ValueNameRegex "ValueName1|ValueName2" -ValueDataRegex "ValueData" -KeyNameRegex "KeyNameToFind1|KeyNameToFind2"
14 |
15 | #>
16 | [CmdletBinding()]
17 | param(
18 | [Parameter(Mandatory, Position=0, ValueFromPipelineByPropertyName)]
19 | [Alias("PsPath")]
20 | # Registry path to search
21 | [string[]] $Path,
22 | # Specifies whether or not all subkeys should also be searched
23 | [switch] $Recurse,
24 | [Parameter(ParameterSetName="SingleSearchString", Mandatory)]
25 | # A regular expression that will be checked against key names, value names, and value data (depending on the specified switches)
26 | [string] $SearchRegex,
27 | [Parameter(ParameterSetName="SingleSearchString")]
28 | # When the -SearchRegex parameter is used, this switch means that key names will be tested (if none of the three switches are used, keys will be tested)
29 | [switch] $KeyName,
30 | [Parameter(ParameterSetName="SingleSearchString")]
31 | # When the -SearchRegex parameter is used, this switch means that the value names will be tested (if none of the three switches are used, value names will be tested)
32 | [switch] $ValueName,
33 | [Parameter(ParameterSetName="SingleSearchString")]
34 | # When the -SearchRegex parameter is used, this switch means that the value data will be tested (if none of the three switches are used, value data will be tested)
35 | [switch] $ValueData,
36 | [Parameter(ParameterSetName="MultipleSearchStrings")]
37 | # Specifies a regex that will be checked against key names only
38 | [string] $KeyNameRegex,
39 | [Parameter(ParameterSetName="MultipleSearchStrings")]
40 | # Specifies a regex that will be checked against value names only
41 | [string] $ValueNameRegex,
42 | [Parameter(ParameterSetName="MultipleSearchStrings")]
43 | # Specifies a regex that will be checked against value data only
44 | [string] $ValueDataRegex
45 | )
46 |
47 | begin {
48 | switch ($PSCmdlet.ParameterSetName) {
49 | SingleSearchString {
50 | $NoSwitchesSpecified = -not ($PSBoundParameters.ContainsKey("KeyName") -or $PSBoundParameters.ContainsKey("ValueName") -or $PSBoundParameters.ContainsKey("ValueData"))
51 | if ($KeyName -or $NoSwitchesSpecified) { $KeyNameRegex = $SearchRegex }
52 | if ($ValueName -or $NoSwitchesSpecified) { $ValueNameRegex = $SearchRegex }
53 | if ($ValueData -or $NoSwitchesSpecified) { $ValueDataRegex = $SearchRegex }
54 | }
55 | MultipleSearchStrings {
56 | # No extra work needed
57 | }
58 | }
59 | }
60 |
61 | process {
62 | foreach ($CurrentPath in $Path) {
63 | Get-ChildItem $CurrentPath -Recurse:$Recurse |
64 | ForEach-Object {
65 | $Key = $_
66 |
67 | if ($KeyNameRegex) {
68 | Write-Verbose ("{0}: Checking KeyNamesRegex" -f $Key.Name)
69 |
70 | if ($Key.PSChildName -match $KeyNameRegex) {
71 | Write-Verbose " -> Match found!"
72 | return [PSCustomObject] @{
73 | Key = $Key
74 | Reason = "KeyName"
75 | }
76 | }
77 | }
78 |
79 | if ($ValueNameRegex) {
80 | Write-Verbose ("{0}: Checking ValueNamesRegex" -f $Key.Name)
81 |
82 | if ($Key.GetValueNames() -match $ValueNameRegex) {
83 | Write-Verbose " -> Match found!"
84 | return [PSCustomObject] @{
85 | Key = $Key
86 | Reason = "ValueName"
87 | }
88 | }
89 | }
90 |
91 | if ($ValueDataRegex) {
92 | Write-Verbose ("{0}: Checking ValueDataRegex" -f $Key.Name)
93 |
94 | if (($Key.GetValueNames() | % { $Key.GetValue($_) }) -match $ValueDataRegex) {
95 | Write-Verbose " -> Match!"
96 | return [PSCustomObject] @{
97 | Key = $Key
98 | Reason = "ValueData"
99 | }
100 | }
101 | }
102 | }
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/Others/Parse-Website.psm1:
--------------------------------------------------------------------------------
1 | <#
2 | DISCLAIMER:
3 |
4 | This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment.
5 |
6 | THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED AS IS
7 | WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
8 | TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
9 |
10 | We grant You a nonexclusive, royalty-free right to use and modify the Sample Code and
11 | to reproduce and distribute the object code form of the Sample Code,
12 | provided that You agree:
13 | (i) to not use Our name, logo, or trademarks to market Your software
14 | product in which the Sample Code is embedded;
15 | (ii) include a valid copyright notice on Your software product in which
16 | the Sample Code is embedded; and
17 | (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and
18 | against any claims or lawsuits, including attorneys' fees, that arise
19 | or result from the use or distribution of the Sample Code.
20 |
21 | Please note: None of the conditions outlined in the disclaimer above will supersede terms and conditions contained within the Premier Customer Services Description.
22 |
23 | ALL CODE MUST BE TESTED BY ANY RECIPIENTS AND SHOULD NOT BE RUN IN A PRODUCTION ENVIRONMENT WITHOUT MODIFICATION BY THE RECIPIENT.
24 |
25 | Author: Mark Warneke
26 | Created: 14-Apr-17
27 |
28 |
29 | HELP
30 |
31 | .SYNOPSIS
32 | Parses a website by url and search criteria
33 |
34 | .DESCRIPTION
35 | Parses a certain ebsite by url based on the parameters provided like tags, classes or ids and returns the value found.
36 | Can be set to exit after one entry is found
37 |
38 | .PARAMETER URL
39 | The URL the script should get the content from.
40 |
41 | .EXAMPLE
42 | C:\PS>
43 | Parse-Website -Url $url -BestMatch -Element $Element -ElementId $id -ElementClass $class
44 |
45 | .INPUTS
46 | $url = the URL to get the content from
47 | $BestMatch = switch if only the first best match is returned or every match found
48 | $Element = the html element to search for
49 | $ElementId = the html id property to search for
50 | $ElementClass = the html class property to search for
51 |
52 |
53 | .OUTPUTS
54 | A string or a list of strings containing the values parsed from a website
55 |
56 | .NOTES
57 | Caveat:
58 | Scraping a site isn’t illegal, but it might void the terms of some sites out there.
59 | Furthermore, if you scrape too often, you might be blocked from the site temporarily or forever.
60 | Don’t get greedy in scraping, or try to use it commercially.
61 |
62 | If a site provides an API, go that route instead,
63 | as API are sanctioned and provided by the company to use,
64 | and require 1% of the resources of loading a full page.
65 |
66 | Finally, some Content Management Systems will never update an existing page,
67 | but create a new one with a new URL and update all links accordingly.
68 | If you’re not careful, you could end up querying a page that will never change.
69 |
70 | #>
71 |
72 |
73 | <#
74 | Parses the website
75 | #>
76 | function Parse-Website {
77 | [CmdletBinding()]
78 | [OutputType([string])]
79 | param(
80 | [Parameter(Mandatory=$true)]
81 | [string]
82 | $Url,
83 |
84 | [int]
85 | $SecondsForRetry = (60*90),
86 |
87 | [int]
88 | $Attampts = 1,
89 |
90 | [switch]
91 | $BestMatch,
92 |
93 | [string]
94 | $ElemantName = "",
95 |
96 | [string]
97 | $ElementId = "",
98 |
99 | [string]
100 | $ElementClass = "text-uppercase"
101 | )
102 |
103 | begin {
104 | Write-Host "Parse site $Url"
105 | }
106 |
107 | process {
108 |
109 |
110 | for ($i = 0; $i -lt $attampts; $i++) {
111 |
112 | # Don't sleep at first try
113 | if (-not ($i -eq 0)) { Start-Sleep -Seconds ($SecondsForRetry) }
114 |
115 | $response = Invoke-WebRequest -Uri $Url
116 | $content = $response.ParsedHtml.body.getElementsByClassName($ElementClass)
117 |
118 | $content | Select-Object -expand innerHTML
119 |
120 | if ($content) {
121 | $return = New-Object PSObject -Property @{
122 | InnerHTML = $content.innerHTML
123 | innerText = $content.innerText
124 | TagName = $content.tagName
125 | ClassName = $conten.className
126 | Id = $content.id
127 | Url = $Url
128 | }
129 | } else {
130 | Write-Verbose "No match found."
131 | }
132 |
133 |
134 | }
135 | }
136 |
137 | end {
138 | return $return
139 | }
140 | }
141 |
142 | # export-modulemember -function Parse-Website
--------------------------------------------------------------------------------
/Others/Show-Calendar.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .Synopsis
3 | Displays a visual representation of a calendar.
4 |
5 | .Description
6 | Displays a visual representation of a calendar. This function supports multiple months
7 | and lets you highlight specific date ranges or days.
8 |
9 | .Parameter Start
10 | The first month to display.
11 |
12 | .Parameter End
13 | The last month to display.
14 |
15 | .Parameter FirstDayOfWeek
16 | The day of the month on which the week begins.
17 |
18 | .Parameter HighlightDay
19 | Specific days (numbered) to highlight. Used for date ranges like (25..31).
20 | Date ranges are specified by the Windows PowerShell range syntax. These dates are
21 | enclosed in square brackets.
22 |
23 | .Parameter HighlightDate
24 | Specific days (named) to highlight. These dates are surrounded by asterisks.
25 |
26 |
27 | .Example
28 | # Show a default display of this month.
29 | Show-Calendar
30 |
31 | .Example
32 | # Display a date range.
33 | Show-Calendar -Start "March, 2010" -End "May, 2010"
34 |
35 | .Example
36 | # Highlight a range of days.
37 | Show-Calendar -HighlightDay (1..10 + 22) -HighlightDate "December 25, 2008"
38 | #>
39 | function Show-Calendar {
40 | param(
41 | [DateTime] $start = [DateTime]::Today,
42 | [DateTime] $end = $start,
43 | $firstDayOfWeek,
44 | [int[]] $highlightDay,
45 | [string[]] $highlightDate = [DateTime]::Today.ToString()
46 | )
47 |
48 | ## Determine the first day of the start and end months.
49 | $start = New-Object DateTime $start.Year,$start.Month,1
50 | $end = New-Object DateTime $end.Year,$end.Month,1
51 |
52 | ## Convert the highlighted dates into real dates.
53 | [DateTime[]] $highlightDate = [DateTime[]] $highlightDate
54 |
55 | ## Retrieve the DateTimeFormat information so that the
56 | ## calendar can be manipulated.
57 | $dateTimeFormat = (Get-Culture).DateTimeFormat
58 | if($firstDayOfWeek)
59 | {
60 | $dateTimeFormat.FirstDayOfWeek = $firstDayOfWeek
61 | }
62 |
63 | $currentDay = $start
64 |
65 | ## Process the requested months.
66 | while($start -le $end)
67 | {
68 | ## Return to an earlier point in the function if the first day of the month
69 | ## is in the middle of the week.
70 | while($currentDay.DayOfWeek -ne $dateTimeFormat.FirstDayOfWeek)
71 | {
72 | $currentDay = $currentDay.AddDays(-1)
73 | }
74 |
75 | ## Prepare to store information about this date range.
76 | $currentWeek = New-Object PsObject
77 | $dayNames = @()
78 | $weeks = @()
79 |
80 | ## Continue processing dates until the function reaches the end of the month.
81 | ## The function continues until the week is completed with
82 | ## days from the next month.
83 | while(($currentDay -lt $start.AddMonths(1)) -or
84 | ($currentDay.DayOfWeek -ne $dateTimeFormat.FirstDayOfWeek))
85 | {
86 | ## Determine the day names to use to label the columns.
87 | $dayName = "{0:ddd}" -f $currentDay
88 | if($dayNames -notcontains $dayName)
89 | {
90 | $dayNames += $dayName
91 | }
92 |
93 | ## Pad the day number for display, highlighting if necessary.
94 | $displayDay = " {0,2} " -f $currentDay.Day
95 |
96 | ## Determine whether to highlight a specific date.
97 | if($highlightDate)
98 | {
99 | $compareDate = New-Object DateTime $currentDay.Year,
100 | $currentDay.Month,$currentDay.Day
101 | if($highlightDate -contains $compareDate)
102 | {
103 | $displayDay = "*" + ("{0,2}" -f $currentDay.Day) + "*"
104 | }
105 | }
106 |
107 | ## Otherwise, highlight as part of a date range.
108 | if($highlightDay -and ($highlightDay[0] -eq $currentDay.Day))
109 | {
110 | $displayDay = "[" + ("{0,2}" -f $currentDay.Day) + "]"
111 | $null,$highlightDay = $highlightDay
112 | }
113 |
114 | ## Add the day of the week and the day of the month as note properties.
115 | $currentWeek | Add-Member NoteProperty $dayName $displayDay
116 |
117 | ## Move to the next day of the month.
118 | $currentDay = $currentDay.AddDays(1)
119 |
120 | ## If the function reaches the next week, store the current week
121 | ## in the week list and continue.
122 | if($currentDay.DayOfWeek -eq $dateTimeFormat.FirstDayOfWeek)
123 | {
124 | $weeks += $currentWeek
125 | $currentWeek = New-Object PsObject
126 | }
127 | }
128 |
129 | ## Format the weeks as a table.
130 | $calendar = $weeks | Format-Table $dayNames -auto | Out-String
131 |
132 | ## Add a centered header.
133 | $width = ($calendar.Split("'n") | Measure-Object -Max Length).Maximum
134 | $header = "{0:MMMM yyyy}" -f $start
135 | $padding = " " * (($width - $header.Length) / 2)
136 | $displayCalendar = " 'n" + $padding + $header + "'n " + $calendar
137 | $displayCalendar.TrimEnd()
138 |
139 | ## Move to the next month.
140 | $start = $start.AddMonths(1)
141 |
142 | }
143 | }
144 | export-modulemember -function Show-Calendar
--------------------------------------------------------------------------------
/Remote/Connect-Mstsc.ps1:
--------------------------------------------------------------------------------
1 | Function Connect-Mstsc {
2 | <#
3 | .SYNOPSIS
4 | Function to connect an RDP session without the password prompt
5 |
6 | .DESCRIPTION
7 | This function provides the functionality to start an RDP session without having to type in the password
8 |
9 | .PARAMETER ComputerName
10 | This can be a single computername or an array of computers to which RDP session will be opened
11 |
12 | .PARAMETER User
13 | The user name that will be used to authenticate
14 |
15 | .PARAMETER Password
16 | The password that will be used to authenticate
17 |
18 | .PARAMETER Credential
19 | The PowerShell credential object that will be used to authenticate against the remote system
20 |
21 | .PARAMETER Admin
22 | Sets the /admin switch on the mstsc command: Connects you to the session for administering a server
23 |
24 | .PARAMETER MultiMon
25 | Sets the /multimon switch on the mstsc command: Configures the Remote Desktop Services session monitor layout to be identical to the current client-side configuration
26 |
27 | .PARAMETER FullScreen
28 | Sets the /f switch on the mstsc command: Starts Remote Desktop in full-screen mode
29 |
30 | .PARAMETER Public
31 | Sets the /public switch on the mstsc command: Runs Remote Desktop in public mode
32 |
33 | .PARAMETER Width
34 | Sets the /w: parameter on the mstsc command: Specifies the width of the Remote Desktop window
35 |
36 | .PARAMETER Height
37 | Sets the /h: parameter on the mstsc command: Specifies the height of the Remote Desktop window
38 |
39 | .NOTES
40 | Name: Connect-Mstsc
41 | Author: Jaap Brasser
42 | DateUpdated: 2016-10-28
43 | Version: 1.2.5
44 | Blog: http://www.jaapbrasser.com
45 |
46 | .LINK
47 | http://www.jaapbrasser.com
48 |
49 | .EXAMPLE
50 | . .\Connect-Mstsc.ps1
51 |
52 | Description
53 | -----------
54 | This command dot sources the script to ensure the Connect-Mstsc function is available in your current PowerShell session
55 |
56 | .EXAMPLE
57 | Connect-Mstsc -ComputerName server01 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force)
58 |
59 | Description
60 | -----------
61 | A remote desktop session to server01 will be created using the credentials of contoso\jaapbrasser
62 |
63 | .EXAMPLE
64 | Connect-Mstsc server01,server02 contoso\jaapbrasser (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force)
65 |
66 | Description
67 | -----------
68 | Two RDP sessions to server01 and server02 will be created using the credentials of contoso\jaapbrasser
69 |
70 | .EXAMPLE
71 | server01,server02 | Connect-Mstsc -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Width 1280 -Height 720
72 |
73 | Description
74 | -----------
75 | Two RDP sessions to server01 and server02 will be created using the credentials of contoso\jaapbrasser and both session will be at a resolution of 1280x720.
76 |
77 | .EXAMPLE
78 | server01,server02 | Connect-Mstsc -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Wait
79 |
80 | Description
81 | -----------
82 | RDP sessions to server01 will be created, once the mstsc process is closed the session next session is opened to server02. Using the credentials of contoso\jaapbrasser and both session will be at a resolution of 1280x720.
83 |
84 | .EXAMPLE
85 | Connect-Mstsc -ComputerName server01:3389 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Admin -MultiMon
86 |
87 | Description
88 | -----------
89 | A RDP session to server01 at port 3389 will be created using the credentials of contoso\jaapbrasser and the /admin and /multimon switches will be set for mstsc
90 |
91 | .EXAMPLE
92 | Connect-Mstsc -ComputerName server01:3389 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Public
93 |
94 | Description
95 | -----------
96 | A RDP session to server01 at port 3389 will be created using the credentials of contoso\jaapbrasser and the /public switches will be set for mstsc
97 |
98 | .EXAMPLE
99 | Connect-Mstsc -ComputerName 192.168.1.10 -Credential $Cred
100 |
101 | Description
102 | -----------
103 | A RDP session to the system at 192.168.1.10 will be created using the credentials stored in the $cred variable.
104 |
105 | .EXAMPLE
106 | Get-AzureVM | Get-AzureEndPoint -Name 'Remote Desktop' | ForEach-Object { Connect-Mstsc -ComputerName ($_.Vip,$_.Port -join ':') -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) }
107 |
108 | Description
109 | -----------
110 | A RDP session is started for each Azure Virtual Machine with the user contoso\jaapbrasser and password supersecretpw
111 |
112 | .EXAMPLE
113 | PowerShell.exe -Command "& {. .\Connect-Mstsc.ps1; Connect-Mstsc server01 contoso\jaapbrasser (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Admin}"
114 |
115 | Description
116 | -----------
117 | An remote desktop session to server01 will be created using the credentials of contoso\jaapbrasser connecting to the administrative session, this example can be used when scheduling tasks or for batch files.
118 | #>
119 | [cmdletbinding(SupportsShouldProcess,DefaultParametersetName='UserPassword')]
120 | param (
121 | [Parameter(Mandatory=$true,
122 | ValueFromPipeline=$true,
123 | ValueFromPipelineByPropertyName=$true,
124 | Position=0)]
125 | [Alias('CN')]
126 | [string[]] $ComputerName,
127 | [Parameter(ParameterSetName='UserPassword',Mandatory=$true,Position=1)]
128 | [Alias('U')]
129 | [string] $User,
130 | [Parameter(ParameterSetName='UserPassword',Mandatory=$true,Position=2)]
131 | [Alias('P')]
132 | [string] $Password,
133 | [Parameter(ParameterSetName='Credential',Mandatory=$true,Position=1)]
134 | [Alias('C')]
135 | [PSCredential] $Credential,
136 | [Alias('A')]
137 | [switch] $Admin,
138 | [Alias('MM')]
139 | [switch] $MultiMon,
140 | [Alias('F')]
141 | [switch] $FullScreen,
142 | [Alias('Pu')]
143 | [switch] $Public,
144 | [Alias('W')]
145 | [int] $Width,
146 | [Alias('H')]
147 | [int] $Height,
148 | [Alias('WT')]
149 | [switch] $Wait
150 | )
151 |
152 | begin {
153 | [string]$MstscArguments = ''
154 | switch ($true) {
155 | {$Admin} {$MstscArguments += '/admin '}
156 | {$MultiMon} {$MstscArguments += '/multimon '}
157 | {$FullScreen} {$MstscArguments += '/f '}
158 | {$Public} {$MstscArguments += '/public '}
159 | {$Width} {$MstscArguments += "/w:$Width "}
160 | {$Height} {$MstscArguments += "/h:$Height "}
161 | }
162 |
163 | if ($Credential) {
164 | $User = $Credential.UserName
165 | $Password = $Credential.GetNetworkCredential().Password
166 | }
167 | }
168 | process {
169 | foreach ($Computer in $ComputerName) {
170 | $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
171 | $Process = New-Object System.Diagnostics.Process
172 |
173 | # Remove the port number for CmdKey otherwise credentials are not entered correctly
174 | if ($Computer.Contains(':')) {
175 | $ComputerCmdkey = ($Computer -split ':')[0]
176 | } else {
177 | $ComputerCmdkey = $Computer
178 | }
179 |
180 | $ProcessInfo.FileName = "$($env:SystemRoot)\system32\cmdkey.exe"
181 | $ProcessInfo.Arguments = "/generic:TERMSRV/$ComputerCmdkey /user:$User /pass:$($Password)"
182 | $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
183 | $Process.StartInfo = $ProcessInfo
184 | if ($PSCmdlet.ShouldProcess($ComputerCmdkey,'Adding credentials to store')) {
185 | [void]$Process.Start()
186 | }
187 |
188 | $ProcessInfo.FileName = "$($env:SystemRoot)\system32\mstsc.exe"
189 | $ProcessInfo.Arguments = "$MstscArguments /v $Computer"
190 | $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
191 | $Process.StartInfo = $ProcessInfo
192 | if ($PSCmdlet.ShouldProcess($Computer,'Connecting mstsc')) {
193 | [void]$Process.Start()
194 | if ($Wait) {
195 | $null = $Process.WaitForExit()
196 | }
197 | }
198 | }
199 | }
200 | }
--------------------------------------------------------------------------------