powershell 代码生成器助手

get-propertyname.ps1
filter IsPropertyForApi {
    if ($_ -match 'public' -and $_ -notmatch "Created|Modified|OrganizationId|(?:\bId\b)")
    {  $_ }
}

function Get-PropertyName {
    param(
         [parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
         [string]$PropertyDeclaration
    )

    process {
        $PropertyDeclaration -match '\w+ \w+\?? (\w+)' | out-null
        $Matches[1]
    }
}

powershell PowerShell参数集

psParameters
#---------------------------------------------------------------
# Evaluating if a Parameter Set has been used
if ($PSCmdlet.ParameterSetName -eq 'InstanceId') {
    $target = @{Key = 'instanceids'; Values = $managedInstanceId}
}
else {
    $target = @{Key = "tag:$tagName"; Values = $TagValue}
}
#---------------------------------------------------------------
#controlling multiple dependencies of parameter choices example
[Parameter(ParameterSetName = 'ScriptblockTag', Mandatory = $true)]
[Parameter(ParameterSetName = 'ScriptPathTag', Mandatory = $true)]
[ValidateSet('prod', 'prod-braveheart', 'gamma', 'alpha')]
[string]$TagValue,

[Parameter(ParameterSetName = 'ScriptblockInstanceId', Mandatory = $true)]
[Parameter(ParameterSetName = 'ScriptPathInstanceId', Mandatory = $true)]
[string[]]$ManagedInstanceId,

[Parameter(ParameterSetName = 'ScriptblockInstanceId', Mandatory = $true)]
[Parameter(ParameterSetName = 'ScriptPathInstanceId', Mandatory = $true)]
[string]$AWSAccountID,

[Parameter(ParameterSetName = 'ScriptblockTag', Mandatory = $true)]
[Parameter(ParameterSetName = 'ScriptblockInstanceId', Mandatory = $true)]
[string]$Scriptblock,

[Parameter(ParameterSetName = 'ScriptPathTag', Mandatory = $true)]
[Parameter(ParameterSetName = 'ScriptPathInstanceId', Mandatory = $true)]
#---------------------------------------------------------------
#validating a parameter input for a file via a validation script
[ValidateScript( {
        if (-Not ($_ | Test-Path) ) {
            throw "File or folder does not exist"
        }
        if (-Not ($_ | Test-Path -PathType Leaf) ) {
            throw "The Path argument must be a file. Folder paths are not allowed."
        }
        if ($_ -notmatch "(\.ps1)") {
            throw "The file specified in the path argument must be either of type ps1"
        }
        return $true
    })]
[System.IO.FileInfo]$ScriptPath,
#---------------------------------------------------------------

powershell create-diagnostic-notebook.ps1 #blog

create-diagnostic-notebook.ps1 #blog

create-diagnostic-notebook.ps1
#
# Purpose: take the diagnostic queries from Glenn Berry
#          and generate a Jupyter Notebook to run in Azure Data Studio
#
# Example usage:
# create-diagnostic-notebook.ps1 -diagnosticScriptPath "C:\Program Files\WindowsPowerShell\Modules\dbatools\0.9.777\bin\diagnosticquery\SQLServerDiagnosticQueries_2019_201901.sql" -notebookOutputPath "diagnostic-notebook.ipynb"
#
[CmdletBinding()]
Param(
    [parameter(Mandatory)]
    [System.IO.FileInfo]$diagnosticScriptPath,
    [System.IO.FileInfo]$notebookOutputPath
)

# 
# Function taken from dbatools https://github.com/sqlcollaborative/dbatools/blob/development/internal/functions/Invoke-DbaDiagnosticQueryScriptParser.ps1
# Parses the diagnostic script and breaks it into individual queries,
# with text and description
#
function Invoke-DbaDiagnosticQueryScriptParser {
    [CmdletBinding(DefaultParameterSetName = "Default")]

    Param(
        [parameter(Mandatory)]
        [ValidateScript( {Test-Path $_})]
        [System.IO.FileInfo]$filename,
        [Switch]$ExcludeQueryTextColumn,
        [Switch]$ExcludePlanColumn,
        [Switch]$NoColumnParsing
    )

    $out = "Parsing file {0}" -f $filename
    write-verbose -Message $out

    $ParsedScript = @()
    [string]$scriptpart = ""

    $fullscript = Get-Content -Path $filename

    $start = $false
    $querynr = 0
    $DBSpecific = $false

    if ($ExcludeQueryTextColumn) {$QueryTextColumn = ""}  else {$QueryTextColumn = ", t.[text] AS [Complete Query Text]"}
    if ($ExcludePlanColumn) {$PlanTextColumn = ""} else {$PlanTextColumn = ", qp.query_plan AS [Query Plan]"}

    foreach ($line in $fullscript) {
        if ($start -eq $false) {
            if (($line -match "You have the correct major version of SQL Server for this diagnostic information script") -or ($line.StartsWith("-- Server level queries ***"))) {
                $start = $true
            }
            continue
        }

        if ($line.StartsWith("-- Database specific queries ***") -or ($line.StartsWith("-- Switch to user database **"))) {
            $DBSpecific = $true
        }

        if (!$NoColumnParsing) {
            if (($line -match "-- uncomment out these columns if not copying results to Excel") -or ($line -match "-- comment out this column if copying results to Excel")) {
                $line = $QueryTextColumn + $PlanTextColumn
            }
        }

        if ($line -match "-{2,}\s{1,}(.*) \(Query (\d*)\) \((\D*)\)") {
            $prev_querydescription = $Matches[1]
            $prev_querynr = $Matches[2]
            $prev_queryname = $Matches[3]

            if ($querynr -gt 0) {
                $properties = @{QueryNr = $querynr; QueryName = $queryname; DBSpecific = $DBSpecific; Description = $queryDescription; Text = $scriptpart}
                $newscript = New-Object -TypeName PSObject -Property $properties
                $ParsedScript += $newscript
                $scriptpart = ""
            }

            $querydescription = $prev_querydescription
            $querynr = $prev_querynr
            $queryname = $prev_queryname
        } else {
            if (!$line.startswith("--") -and ($line.trim() -ne "") -and ($null -ne $line) -and ($line -ne "\n")) {
                $scriptpart += $line + "`n"
            }
        }
    }

    $properties = @{QueryNr = $querynr; QueryName = $queryname; DBSpecific = $DBSpecific; Description = $queryDescription; Text = $scriptpart}
    $newscript = New-Object -TypeName PSObject -Property $properties
    $ParsedScript += $newscript
    $ParsedScript
}


$cells = @()

Invoke-DbaDiagnosticQueryScriptParser $diagnosticScriptPath |
    Where-Object { -not $_.DBSpecific } |
    ForEach-Object {
        $cells += [pscustomobject]@{cell_type = "markdown"; source = "## $($_.QueryName)`n`n$($_.Description)" }
        $cells += [pscustomobject]@{cell_type = "code"; source = $_.Text }
    }

$preamble = @"
{
    "metadata": {
        "kernelspec": {
            "name": "SQL",
            "display_name": "SQL",
            "language": "sql"
        },
        "language_info": {
            "name": "sql",
            "version": ""
        }
    },
    "nbformat_minor": 2,
    "nbformat": 4,
    "cells":
"@


$preamble | Out-File $notebookOutputPath 
$cells | ConvertTo-Json | Out-File -FilePath $notebookOutputPath -Append
"}}" | Out-File -FilePath $notebookOutputPath -Append

powershell 在Windows venv中运行iot模拟器

在Windows venv中运行iot模拟器

run-in-penv.ps1
docker build  --rm -f "c:\g\cse\mqtt\app\mosquitto_authn\modules\sender\Dockerfile.amd64" -t localhost:5000/sender:0.0.1-amd64 "c:\g\cse\mqtt\app\mosquitto_authn\modules\sender" ; if ($?) { iotedgehubdev start -d "c:\g\cse\mqtt\app\mosquitto_authn\config\deployment.amd64.json" -v }

powershell 娱乐和游戏

使用参数验证简化PowerShell脚本|脚本<https://devblogs.microsoft.com/scripting/simplify-your-powershell-script-with-parameter-validation/> <br/>使用参数集简化PowerShell命令脚本<https://devblogs.microsoft.com/scripting/use-parameter-sets-to-simplify-powershell-commands/>

show_available_for_bbc_links.ps1

"https://www.bbc.co.uk/programmes/b01q9tb1/episodes/guide","https://www.bbc.co.uk/programmes/b00lmcxj/episodes/guide","https://www.bbc.co.uk/programmes/b00tg191/episodes/guide","https://www.bbc.co.uk/programmes/b07hk30x/episodes/guide" | 
% { $response = invoke-webrequest $_ ; $title = $response.ParsedHtml.getElementsByTagName('div') | ? { $_.className() -eq 'br-masthead__title' } | % { $_.innerText } ; $available = $response.ParsedHtml.getElementsByTagName('li') | ? { $_.className() -eq 'pull--left' } | % { $_.innerText } | ? { $_ -match 'Available' } ; write-host "$title : $available"
}

filling_buckets.ps1
Mkdir c:\temp
Mkdir c:\temp\sides
(1..5 | % { "b$_" }) | set-content -Encoding UTF8 C:\temp\Sides\buckets.txt
$buckets = gc C:\temp\Sides\buckets.txt

1..17 | % { "i$_" } | set-content -Encoding UTF8 C:\temp\Sides\items.txt
$items = (gc C:\temp\Sides\items.txt)

$itemsToBucket = ($items | select -first $numberBuckets)
$itemsToShift = ($items | select -skip $numberBuckets)
$itemsForNextIteration = $itemsToShift + $itemsToBucket

$bucketed = ($buckets | % { $item,$remaining = $itemsToBucket ; $itemsToBucket = $remaining ; new-object psobject -property @{ "bucket" = $_ ; "item" = $item } })

$itemsBucketed = ($bucketed | select -ExpandProperty item )
$itemsToShift = ($items | select -skip $itemsBucketed.Count )
$itemsForNextIteration = $itemsToShift + $itemsBucketed

powershell PowerShell配置文件

PowerShell配置文件

profile.ps1
<#
#   ┌          ┐
#     sources
#   └          ┘
https://gist.github.com/cloudRoutine/87c17655405cd8b1eac7
https://gist.github.com/furzeface (not sure where profile.ps1 URL disappeared to)
#>

# If this script is throwing an error near a Unicode symbol try resaving the file as UTF-8 with BOM
$psmodules = ";~\Documents\WindowsPowerShell\Modules"
# sometimes the module paths has been fucked before posh loads, but that won't stop us
$env:PSModulePath = $env:PSModulePath + $psmodules

# Set the OutputEncoding to Unicode so that the λ renders properly

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8


# The Host check is necessary if you don't want these to load in `Windows PowerShell ISE Host`

if ($host.Name -eq 'ConsoleHost')
{
    # https://stackoverflow.com/a/28740512
    # http://psget.net/
    if (Get-Module -ListAvailable -Name PsGet) {
        continue;
    } else {
        (new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex
    }
    # TODO: module array + Install-Module <module_item> + Import-Module <module_item>
    Import-Module PsGet
    Import-Module PSReadline
    Import-Module posh-ssh
    Import-Module posh-git
    Import-Module powerls
    Import-Module PSColor
    Import-Module TabExpansion++



    # Load all of the scripts in the script repository 
    select "${psmodules}\script-repo\*.ps1" | %{.$_} 


    Set-PSReadlineKeyHandler -Key Ctrl+Delete    -Function KillWord
    Set-PSReadlineKeyHandler -Key Ctrl+Backspace -Function BackwardKillWord
    Set-PSReadlineKeyHandler -Key Shift+Backspace -Function BackwardKillWord
    Set-PSReadlineKeyHandler -Key UpArrow        -Function HistorySearchBackward
    Set-PSReadlineKeyHandler -Key DownArrow      -Function HistorySearchForward
    Set-PSReadlineKeyHandler -Key Tab            -Function Complete

    $Host.PrivateData.ErrorBackgroundColor   = $Host.UI.RawUI.BackgroundColor
    $Host.PrivateData.WarningBackgroundColor = $Host.UI.RawUI.BackgroundColor
    $Host.PrivateData.VerboseBackgroundColor = $Host.UI.RawUI.BackgroundColor

    Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent)

    function prompt
    {
        $g = [ConsoleColor]::Green
        $h = [ConsoleColor]::DarkGray

        $realLASTEXITCODE = $LASTEXITCODE
        $Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor
        $loc = $(Get-Location)

        Write-Host `r
        Write-Host $loc -n -f $g
        Write-VcsStatus
        Write-Host `r
        Write-Host "λ»" -n -f $h

        $global:LASTEXITCODE = $realLASTEXITCODE
        Return ' '
    }
    Pop-Location
    Start-SshAgent -Quiet

}

#   ┌                 ┐
#     general aliases
#   └                 ┘

# Yo dawg, I heard you like unix (@tawashley, 2015)
New-Alias cl clear
New-Alias ll dir

#   ┌                   ┐
#     directory aliases
#   └                   ┘

# Functions are required for multi-line commands
Function GoBackUpOne { cd ..; dir; }
Function GoToDesktop { c:;  cd .\Desktop; dir}
Function GoToHomeDirectory { cd ~; dir } 

# Bind alias with function call
New-Alias .. GoBackUpOne
New-Alias ~ GoToHomeDirectory


#   ┌                 ┐
#     posh management
#   └                 ┘

function poshver { $PSVersionTable.PSVersion | write-host }

 # Call with `. rlp` to reload profile
function rprof  {   write-host " `n Δ Reloading Profile...      " -foregroundcolor darkgreen
                    . $profile
                }

function rpath  {   write-host " `n Δ Reloading Environment Variables from PATH...      " -foregroundcolor darkgreen
                    $env:Path = ""
                    $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" +
                                [System.Environment]::GetEnvironmentVariable("Path","User")
                }

function delfr  {   Param($target)
                    del $target -force -recurse
                }

function dir    {   Param($dirName)
                    ni $dirName -type directory
                }

Set-Alias github    "~\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\GitHub, Inc\GitHub.appref-ms"

function repos   {cd  "~\Github"   }

# . subl loads the current directory in sublime
# Set-Alias subl      "~\Portable Software\Sublime Text\sublime_text.exe"
# Set-Alias atom      "~\Change\to\atom\atom.exe"

# function Edit-Profile { subl $Profile }
# Set-Alias ep    Edit-Profile

# Set-Alias open      Invoke-Item
# function pics      { open '~\Pictures'  }
# function books     { open '~\Ebooks'   }

# function progproj  { cd     '~\Programming Projects'    }
# function progwrite { cd     '~\Programming Writing'     }
# function portsoft  { open   '~\Portable Software'       }

#   ┌        ┐
#     F# DEV
#   └        ┘

# Set-Alias msbuild4  "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe"
# Set-Alias msbuild12 "C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe"
# Set-Alias vs14      "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"

# function  load-templates { write-host " `Δ loading visual studio 2015 templates from - C:\Users\Jared\Documents\Visual Studio 2015\Templates       " -foregroundcolor darkgreen
#                             vs14 /installvstemplates }

# function scaffoldfs {   Param($projectName)
#                         git clone "https://github.com/fsprojects/ProjectScaffold.git"
#                         cd ProjectScaffold
#                         echo "`nRemoving original .git folder..."
#                         Remove-Item ".git" -force -recurse
#                         echo " done.`n"
#                         cd ..
#                         if ($projectName -eq "") {$projectName = "fsharp_oss_project"}
#                         echo "`nRenaming project $projectName `n"
#                         Rename-Item ProjectScaffold $projectName
#                         cd $projectName
#                         git init
#                         & ".\build.cmd"
#                     }

# function scaffold-into {  ($directory)
#                         mkdir "temp_scaffold" | cd "temp_scaffold"
#                         echo "`n Cloning Project Scaffold"
#                         git clone "https://github.com/fsprojects/ProjectScaffold.git"
#                         cd ProjectScaffold | Remove-Item ".git" -force -recurse
#                         cd .. | echo "`n Copying Scaffold files into " + $directory
#                         Copy-Item ProjectScaffold\* $directory
#                         cd ..
#                         echo "`n Cleaning up temporary scaffold files " + $directory
#                         Remove-Item "temp_scaffold" -Force -Recurse
#                         echo "`n COMPLETE! You can run the Scaffold setup with '.\build.cmd' "
#                     }



#   ┌             ┐
#     GIT HELPERS
#   └             ┘

function glog   {   git $args --no-pager log --oneline --all --graph --decorate `
                    --pretty=format:"%C(yellow)%h%Creset | %C(magenta)%ad%Creset | %Cred%d%Creset %Creset%s  %C(green dim) < %cn > %Creset " `
                    --date=short                 }

function update {   git pull --rebase --prune $@
                    git submodule update --init --recursive
                }
function save   {   git add -A
                    git commit -m 'SAVEPOINT'
                }
function wipe   {   git add -u
                    git commit -m "WIPE"
                }
function amend  {   git commit -a --amend --no-edit  }

function amend-with
                {   Param($commitMessage)
                    git commit -a --amend -m $commitMessage   }

function undo   {   reset HEAD~1 --mixed    }

function softreset { git reset --soft HEAD~1 }

function wash   {   git add -A
                    git commit -qm 'WIPE SAVEPOINT'
                    git reset HEAD~1 --hard }

function pop-commit { git reset HEAD^ }


function git-remotes
  {  git remote -v }

function set-remote  ($remote, $url)
    {  git remote set-url $remote  $url     }

function co     {   Param($branch)
                    git checkout $branch           }

function ec     {   git config --global -e  }

function cm     {   Param($commitMessage)
                    git add -A | git commit -m $commitMessage }

function gitdrop { git checkout -- . }

function tracking { Param($branch)
    git ls-tree -r $branch --name-only
}

function untrack {  Param($file)
    git rm --cached -f $file
}

powershell 获取SQL Server信息

get_product_name.sql
SELECT
  CASE 
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '8%' THEN 'SQL2000'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '9%' THEN 'SQL2005'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.0%' THEN 'SQL2008'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.5%' THEN 'SQL2008 R2'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '11%' THEN 'SQL2012'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '12%' THEN 'SQL2014'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '13%' THEN 'SQL2016'     
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '14%' THEN 'SQL2017' 
     ELSE 'unknown'
  END AS MajorVersion,
  SERVERPROPERTY('ProductLevel') AS ProductLevel,
  SERVERPROPERTY('Edition') AS Edition,
  SERVERPROPERTY('ProductVersion') AS ProductVersion
get_version.sql
SELECT @@VERSION
get_product_key.ps1
function Get-SQLserverKey {
 
    param ($targets = ".")
    $hklm = 2147483650 #HK_LOCAL_MACHINE
    $regPath = $null
    $baseRegPath = "SOFTWARE\Microsoft\Microsoft SQL Server\"
 
    ##SQL2016 130
    ##SQL2014 120
    ##SQL2012 110
    ##SQL2008R2 105
    ##SQL2008 100
    ##SQL2005 90
    $sqlVersionArray = "90","100","105","110","120","130"
 
 
    $regValue1 = "DigitalProductId"
    $regValue2 = "PatchLevel"
    $regValue3 = "Edition"
 
    ##loop through all Hosts
    Foreach ($target in $targets) {
 
        ##loop through all potential SQL versions
        Foreach($sqlVersion in $sqlVersionArray) {
            $regPath = $baseRegPath + $sqlVersion + "\Tools\Setup"
 
            $productKey = $null
            $win32os = $null
            $wmi = [WMIClass]"\\$target\root\default:stdRegProv"
            $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue1)
 
            if($data.uValue -ne $null) {
                [string]$SQLver = $wmi.GetstringValue($hklm,$regPath,$regValue2).svalue
                [string]$SQLedition = $wmi.GetstringValue($hklm,$regPath,$regValue3).svalue
 
                $binArray = $null
 
                #Array size is dependant on SQL Version
                if([convert]::ToInt32($sqlVersion,10) -gt 105) {
                    $binArray = ($data.uValue)[0..16]
                }
                else { 
                    $binArray = ($data.uValue)[52..66]
                }
 
                $charsArray = “BCDFGHJKMPQRTVWXY2346789”.toCharArray()
 
                ## decrypt base24 encoded binary data
                For ($i = 24; $i -ge 0; $i--) {
                    $k = 0
                    For ($j = 14; $j -ge 0; $j--) {
                    $k = $k * 256 -bxor $binArray[$j]
                    $binArray[$j] = [math]::truncate($k / 24)
                    $k = $k % 24
                    }
                    $productKey = $charsArray[$k] + $productKey
                    If (($i % 5 -eq 0) -and ($i -ne 0)) {
                        $productKey = "-" + $productKey
                    }
                }
                $win32os = Get-WmiObject Win32_OperatingSystem -computer $target
                $obj = New-Object Object
                $obj | Add-Member Noteproperty Computer -value $target
                $obj | Add-Member Noteproperty OSCaption -value $win32os.Caption
                $obj | Add-Member Noteproperty OSArch -value $win32os.OSArchitecture
                $obj | Add-Member Noteproperty SQLver -value $SQLver
                $obj | Add-Member Noteproperty SQLedition -value $SQLedition
                $obj | Add-Member Noteproperty ProductKey -value $productkey
                $obj
            }
        }
    }
}
##Dummyproof local execution for people who don't PowerShell
Get-SQLserverKey

powershell 字符串示例

字符串示例

Powershell String.ps1
# Like
'hello' -like '?ello'
'hello' -notlike '?ello'
'hello' -like '*o'
'aabcc' -match 'a*b?c+'

# contains
'hello','world','ian' -contains 'ian'

# replace 
'hello ian' -replace 'ian','ltc'

# Split
'A B C DE' -split ' '

# Join
'A','B','C' -join ','

'ian' -match 'Ian'
'ian' -cmatch 'Ian' #case-sensitive

powershell [Установкаwordpressv0.5]быстраяустановкаwordpressчерезwp-cliснастройками#tags:wordpress,wp-cli,ph1

[Установкаwordpressv0.5]быстраяустановкаwordpressчерезwp-cliснастройками#tags:wordpress,wp-cli,ph1

wp_install.ps1
#------------ Данные сайта ------------
$dbname = "test" #Имя базы данных
$dbuser = "root" #Пользователь базы данных
$table_prefix = "wp_" #Префикс таблиц
$url = "test.loc" #url сайта
$title = "test website" #Тайтл сайта
$admin_user = "admin" #Логин админа
$admin_password = "1234567" #Пароль админа
$admin_email="mail@example.ru" #Email админа

#------------ Выполнение команд ------------
wp core download --locale="ru_RU" #Скачивание wordpress с русским языком
wp core config --dbname=$dbname --dbuser=$dbuser #Имя и логин базы данных
wp config set table_prefix $table_prefix #Префикс таблиц
wp db create
wp core install --url=$url --title=$title --admin_user=$admin_user --admin_password=$admin_password --admin_email=$admin_email

#------------ Плагины ------------
wp plugin delete hello
wp plugin install cyr3lat --activate
wp plugin install classic-editor --activate
wp plugin install contact-form-7 --activate

#------------ Часовой пояс +6 ------------
wp option update gmt_offset 6

#------------ Настройки постоянных ссылок ------------
wp option update permalink_structure `/%year%/%monthnum%/%day%/%postname%/`

powershell loopback adapter配置ps

loopback.ps1
Install-Module -Name LoopbackAdapter -MinimumVersion 1.2.0.0 -Force
Import-Module -Name LoopbackAdapter

# The name for the loopback adapter interface that will be created.
$loopback_name = 'VIP1'

# The name for the servers main network interface. This will be updated to allow weak host send/recieve which is most likely required for the traffic to work for the loopback interface.
$primary_interface = 'Primary NIC'

# The IPv4 address that you would like to assign to the loopback interface along with the prefix length (eg. if the IP is routed to the server usually you would set the prefix length to 32).
$loopback_ipv4 = '216.247.237.245'
$loopback_ipv4_length = '32'

# The IPv6 address that you would like to assign to the loopback interface along with the prefix length (eg. if the IP is routed to the server usually you would set the prefix length to 128). If you are not adding an IPv6 address do not set these variables.
# $loopback_ipv6 = 'fffa::1'
# $loopback_ipv6_length = '128'

New-LoopbackAdapter -Name $loopback_name -Force
interface_loopback = Get-NetAdapter -Name $loopback_name
interface_main = Get-NetAdapter -Name $primary_interface

Set-NetIPInterface -InterfaceIndex $interface_loopback.ifIndex -InterfaceMetric "254" -WeakHostReceive Enabled -WeakHostSend Enabled -DHCP Disabled
Set-NetIPInterface -InterfaceIndex $interface_main.ifIndex -WeakHostReceive Enabled -WeakHostSend Enabled
Set-NetIPAddress -InterfaceIndex $interface_loopback.ifIndex -SkipAsSource $True
Get-NetAdapter $loopback_name | Set-DNSClient –RegisterThisConnectionsAddress $False
# Set the IPv4 address
New-NetIPAddress -InterfaceAlias $loopback_name -IPAddress $loopback_ipv4 -PrefixLength $loopback_ipv4_length -AddressFamily ipv4

# Set the IPv6 address - Uncomment this if required
# New-NetIPAddress -InterfaceAlias $loopback_name -IPAddress $loopback_ipv6 -PrefixLength $loopback_ipv6_length -AddressFamily ipv6
Disable-NetAdapterBinding -Name $loopback_name -ComponentID ms_msclient
Disable-NetAdapterBinding -Name $loopback_name -ComponentID ms_pacer
Disable-NetAdapterBinding -Name $loopback_name -ComponentID ms_server
Disable-NetAdapterBinding -Name $loopback_name -ComponentID ms_lltdio
Disable-NetAdapterBinding -Name $loopback_name -ComponentID ms_rspndr