powershell MS SQL Powershell使用SQLPS创建数据库

MS SQL Powershell使用SQLPS创建数据库

MS SQL Powershell Create Database Using SQLPS.ps1
# Files and file groups are automatically created for the database.
cd \sql\localhost\
$srv = Get-Item default

$db = New-Object -TypeName 
  Microsoft.SqlServer.Management.Smo.Database -argumentlist $srv, "MyDB"  
 
$db.Create()  

$db = $srv.Databases["MyDB"]
$db.CreateDate

$db.Drop()

powershell MS SQL Powershell加载SQL Server PS模块

MS SQL Powershell加载SQL Server PS模块

MS SQL Powershell Load SQL Server PS Module.ps1
# Load the SQL Server PowerShell Module.
PS C:\> sqlps
#Microsoft (R) SQL Server (R) PowerShell
#Version 12.0.5557.0
#Copyright (c) 2014 Microsoft. All rights reserved.

# Once switched to the SQLSERVER drive >
PS SQLSERVER:\> get-childitem

powershell MS SQL Powershell连接到SQL Server

MS SQL Powershell连接到SQL Server

PS Connecting to SQL Server.ps1
[string] $userName = "<userName>"
[string] $pwd = "<pwd>"
[string] $connStr = "Server=localhost;Database=master;
                     User ID=$userName;Password=$pwd;
                     Encrypt=false;TrustServerCertificate=False;
                     Connection Timeout=30;"

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connStr
$connection.Open();

$cmd = $connection.CreateCommand()
$cmd.CommandText = "SELECT @@ServerName"

$reader = $cmd.ExecuteReader()
$reader.HasRows

$cmd.Dispose()
$connection.Close()

#Executing
# D:\PowershellScripts>& '.\PS Connecting to SQL Server.ps1'

powershell Boxstarter脚本(bitcrazed)

保存自https://gist.github.com/bitcrazed/c788f9dcf1d630340a19

boxstarter.ps1
# Description: Boxstarter Script
# Author: Rich Turner <rich@bitcrazed.com>
# Last Updated: 2019-07-08
#
# Run this Boxstarter by calling the following from an **ELEVATED PowerShell instance**:
#     `set-executionpolicy Unrestricted`
#     `. { iwr -useb https://boxstarter.org/bootstrapper.ps1 } | iex; get-boxstarter -Force`
#     `Install-BoxstarterPackage -DisableReboots -PackageName <URL-TO-RAW-GIST>`

#---- TEMPORARY ---
  Disable-UAC
  
#--- Used to uninstall unwanted default apps ---
function Remove-App 
{	
    Param ([string]$appName)
    
    Write-Output "Trying to remove $appName"
    
    Get-AppxPackage $appName -AllUsers | Remove-AppxPackage
    
    Get-AppXProvisionedPackage -Online | Where DisplayNam -like $appName | Remove-AppxProvisionedPackage -Online
}
        
#--- Uninstall unwanted default apps ---
$applicationList = @(	
    "Microsoft.3DBuilder"
    "Microsoft.CommsPhone"
    "Microsoft.Getstarted"
    "*MarchofEmpires*"
    "Microsoft.GetHelp"
    "Microsoft.Messaging"
    "*Minecraft*"
    "Microsoft.MicrosoftOfficeHub"
    "Microsoft.WindowsPhone"
    "*Solitaire*"
    "Microsoft.MicrosoftStickyNotes"
    "Microsoft.Office.Sway"
    "Microsoft.XboxApp"
    "Microsoft.XboxIdentityProvider"
    "Microsoft.NetworkSpeedTest"
    "Microsoft.Print3D"

    #Non-Microsoft
    "*Autodesk*"
    "*BubbleWitch*"
    "king.com.CandyCrush*"
    "*Dell*"
    "*Dropbox*"
    "*Facebook*"
    "*Keeper*"
    "*Plex*"
    "*.Duolingo-LearnLanguagesforFree"
    "*.EclipseManager"
    "ActiproSoftwareLLC.562882FEEB491" # Code Writer
    "*.AdobePhotoshopExpress");

foreach ($app in $applicationList) {
    Remove-App $app
}

#--- Windows Features ---
    Set-WindowsExplorerOptions -EnableShowFileExtensions ### -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles
    Set-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\AppModelUnlock -Name AllowDevelopmentWithoutDevLicense -Value 1
    Set-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name NavPaneExpandToCurrentFolder -Value 1
    Set-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name NavPaneShowAllFolders -Value 1
    Set-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name LaunchTo -Value 1
    Set-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name MMTaskbarMode -Value 2

    Enable-RemoteDesktop

#--- PowerShell utilities
    Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
    Install-Module DirColors
    Install-Module posh-git

#--- Install Windows features
    choco install -y Microsoft-Hyper-V-All -source windowsFeatures
    choco install -y Microsoft-Windows-Subsystem-Linux -source WindowsFeatures 
  
#--- Install Git ---
  choco install -y git -params '"/GitAndUnixToolsOnPath /WindowsTerminal"'
  RefreshEnv # Refresh env due to Git install

#--- Tools ---
  choco install -y 7Zip
  choco install -y vim
  choco install -y BeyondCompare
  choco install -y Paint.net
  choco install -y Sysinternals
  
#--- Install Dev Tools ---
  #choco install -y ruby
  #choco install -y python
  choco install -y nodejs
  choco install -y visualstudiocode
  
#--- Install Visual Studio 2019 ---
  # See this for install args: https://chocolatey.org/packages/VisualStudio2019Community  
  choco install -y visualstudio2019enterprise
  choco install -y visualstudio2019-workload-universal
  choco install -y visualstudio2019-workload-manageddesktop
  choco install -y visualstudio2019-workload-netcoretools
  choco install -y visualstudio2019-workload-nativecrossplat
  choco install -y visualstudio2019-workload-nativedesktop
  choco install -y visualstudio2019-workload-azure

#--- Misc Tools ---
  choco install -y Vlc
  
#--- Restore Temporary Settings ---
    Enable-UAC
    Enable-MicrosoftUpdate
    Install-WindowsUpdate -acceptEula

$email = Read-Host "Enter your email address" 
ssh-keygen -t rsa -b 4096 -C "$email"

if (Test-Path d:) { $drive = 'd' }
else { $drive = 'c' }

if (!@(Test-Path ${drive}:\dev\)) { mkdir ${drive}:\dev\ }
cd ${drive}:\dev

if (!@(Test-Path ${drive}:\dev\powerrazzle)) {
  git clone git@github.com:bitcrazed/powerrazzle
}

powershell 提示代码

ps-prompt.ps1
function prompt {
  # Required Functions - shorten-path
  function shorten-path {
    $loc = $PWD.Path -replace '^[^:]+::', ''
    return ($loc)
  }
  $isAdmin = (
  [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
  [Security.Principal.WindowsBuiltInRole]::Administrator)
  if ($isAdmin) { $uiadmin = 'Administrator: '}
  if ($psISE) { $host.UI.RawUI.WindowTitle = '{0} ISE |> {1} |> {2}' -f $uiadmin,$env:USERNAME,$(shorten-path) }
  else { $host.UI.RawUI.WindowTitle = '{0} PS |> {1} |> {2}' -f $uiadmin,$env:USERNAME,$(shorten-path) }
  Write-Host -Object "$([char]0x0A7) " -NoNewline -ForegroundColor Cyan
  Write-Host -Object ([net.dns]::GetHostName()) -NoNewline -ForegroundColor Green
  Write-Host -Object ' {' -NoNewline -ForegroundColor DarkCyan
  Write-Host -Object (shorten-path) -NoNewline -ForegroundColor Cyan
  Write-Host -Object '}' -NoNewline -ForegroundColor DarkCyan
  return ' '
}

powershell ISE插件模板

ISE-Addon-template.ps1
#region SAMPLE - Ctrl+Shift+G
$Display = 'SAMPLE'
$Action = {Get-ChildItem}
$Shortcut = 'Ctrl+Shift+G'

$null = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add($Display,$Action,$Shortcut)
#endregion

powershell PSDefaultParameterValues.ps1

$ PSDefaultParameterValues - PowerShell配置文件值

PSDefaultParameterValues.ps1
$gittoken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
$gistcred = New-Object pscredential 'XXXXXX', ( ConvertTo-SecureString -String $gittoken -AsPlainText -Force )
$PSDefaultParameterValues = @{
	'Get-ChildItem:Force'=$True
	'Get-ChildItem:ErrorAction'='SilentlyContinue'
	'Format-Table:AutoSize'=$True
	'Get-Gist:Credential'=$gistcred
	'Get-GitHubRepository:AccessToken'=$gittoken
	'Out-Default:OutVariable'='stdout'
	'Save-Module:Path'='X:\XXX\XXX\modules'
	'Save-Module:Verbose'=$True
	'Out-File:Encoding'='default'
	'Get-Help:ShowWindow'=$True
}

powershell 蓝牙模块

打开/关闭蓝牙或重置蓝牙。 <br/>设置 - 蓝牙<br/>禁用 - 蓝牙<br/>启用 - 蓝牙<br/>重置 - 蓝牙

Bluetooth.psm1
function Set-Bluetooth {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [ValidateSet('On', 'Off', 'Reset')]
        [string]
        $State
    )
    begin {
        Add-Type -AssemblyName System.Runtime.WindowsRuntime
    }

    process {
        if ((Get-Service -Name bthserv).Status -eq 'Stopped') { Start-Service -Name bthserv }
    
        $asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
        function Await($WinRtTask, $ResultType) {
            $asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
            $netTask = $asTask.Invoke($null, @($WinRtTask))
            $netTask.Wait(-1) | Out-Null
            $netTask.Result
        }
        [Windows.Devices.Radios.Radio, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        [Windows.Devices.Radios.RadioAccessStatus, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        Await ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
        $radios = Await ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]])
        $bluetooth = $radios | Where-Object { $_.Kind -eq 'Bluetooth' }
        if ($bluetooth.State -ne $State) {
            switch($State) {
                'Reset' {
                    [Windows.Devices.Radios.RadioState, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
                    try {
                        if ((Await ($bluetooth.SetStateAsync('Off')) ([Windows.Devices.Radios.RadioAccessStatus])) -eq 'Allowed') {
                            if ((Await ($bluetooth.SetStateAsync('On')) ([Windows.Devices.Radios.RadioAccessStatus])) -eq 'Allowed') {
                                Write-Host "Bluetooth reset."
                            }
                            else {
                                Write-Host "Bluetooth could not be turned on."
                            }
                        }
                        else {
                            Write-Host "Bluetooth could not be turned off."
                        }
                    }
                    catch {
                        Throw $_
                    }
                    break
                }
                default {
                    [Windows.Devices.Radios.RadioState, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
                    try {
                        if ((Await ($bluetooth.SetStateAsync($State)) ([Windows.Devices.Radios.RadioAccessStatus])) -eq 'Allowed') {
                            Write-Host "Bluetooth turned $($State.ToLower())."
                        }
                        else {
                            Write-Host "Bluetooth could not be turned $($State.ToLower())."
                        }
                    }
                    catch {
                        Throw $_
                    }
                }
            }
        }
        else {
            Write-Host "Bluetooth is already $($State.ToLower())."
        }
    }

    end {

    }
}

function Disable-Bluetooth {
    [CmdletBinding()]
    Param ()
    begin {
        Add-Type -AssemblyName System.Runtime.WindowsRuntime
        $State = 'Off'
    }

    process {
        if ((Get-Service -Name bthserv).Status -eq 'Stopped') { Start-Service -Name bthserv }
    
        $asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
        function Await($WinRtTask, $ResultType) {
            $asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
            $netTask = $asTask.Invoke($null, @($WinRtTask))
            $netTask.Wait(-1) | Out-Null
            $netTask.Result
        }
        [Windows.Devices.Radios.Radio, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        [Windows.Devices.Radios.RadioAccessStatus, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        Await ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
        $radios = Await ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]])
        $bluetooth = $radios | Where-Object { $_.Kind -eq 'Bluetooth' }
        if ($bluetooth.State -ne $State) {
            [Windows.Devices.Radios.RadioState, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
            try {
                if ((Await ($bluetooth.SetStateAsync($State)) ([Windows.Devices.Radios.RadioAccessStatus])) -eq 'Allowed') {
                    Write-Host "Bluetooth turned $($State.ToLower())."
                }
                else {
                    Write-Host "Bluetooth could not be turned $($State.ToLower())."
                }
            }
            catch {
                Throw $_
            }
        }
        else {
            Write-Host "Bluetooth is already $($State.ToLower())."
        }
    }

    end {

    }
}

function Enable-Bluetooth {
    [CmdletBinding()]
    Param ()
    begin {
        Add-Type -AssemblyName System.Runtime.WindowsRuntime
        $State = 'On'
    }

    process {
        if ((Get-Service -Name bthserv).Status -eq 'Stopped') { Start-Service -Name bthserv }
    
        $asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
        function Await($WinRtTask, $ResultType) {
            $asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
            $netTask = $asTask.Invoke($null, @($WinRtTask))
            $netTask.Wait(-1) | Out-Null
            $netTask.Result
        }
        [Windows.Devices.Radios.Radio, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        [Windows.Devices.Radios.RadioAccessStatus, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        Await ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
        $radios = Await ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]])
        $bluetooth = $radios | Where-Object { $_.Kind -eq 'Bluetooth' }
        if ($bluetooth.State -ne $State) {
            [Windows.Devices.Radios.RadioState, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
            try {
                if ((Await ($bluetooth.SetStateAsync($State)) ([Windows.Devices.Radios.RadioAccessStatus])) -eq 'Allowed') {
                    Write-Host "Bluetooth turned $($State.ToLower())."
                }
                else {
                    Write-Host "Bluetooth could not be turned $($State.ToLower())."
                }
            }
            catch {
                Throw $_
            }
        }
        else {
            Write-Host "Bluetooth is already $($State.ToLower())."
        }
    }

    end {

    }
}

function Reset-Bluetooth {
    [CmdletBinding()]
    Param ()
    begin {
        Add-Type -AssemblyName System.Runtime.WindowsRuntime
        $State = 'Reset'
    }

    process {
        if ((Get-Service -Name bthserv).Status -eq 'Stopped') { Start-Service -Name bthserv }
    
        $asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
        function Await($WinRtTask, $ResultType) {
            $asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
            $netTask = $asTask.Invoke($null, @($WinRtTask))
            $netTask.Wait(-1) | Out-Null
            $netTask.Result
        }
        [Windows.Devices.Radios.Radio, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        [Windows.Devices.Radios.RadioAccessStatus, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        Await ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
        $radios = Await ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]])
        $bluetooth = $radios | Where-Object { $_.Kind -eq 'Bluetooth' }
        [Windows.Devices.Radios.RadioState, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null
        try {
            if ((Await ($bluetooth.SetStateAsync('Off')) ([Windows.Devices.Radios.RadioAccessStatus])) -eq 'Allowed') {
                if ((Await ($bluetooth.SetStateAsync('On')) ([Windows.Devices.Radios.RadioAccessStatus])) -eq 'Allowed') {
                    Write-Host "Bluetooth reset."
                }
                else {
                    Write-Host "Bluetooth could not be turned on."
                }
            }
            else {
                Write-Host "Bluetooth could not be turned off."
            }
        }
        catch {
            Throw $_
        }
    }

    end {

    }
}

powershell 停止 - 管道

在PowerShell中的* System.Windows.Forms.Form *中的** ForEeach **中使用** break **时遇到*未处理的异常'。作为一种解决方法,使用此CmdLet将停止当前管道而不是使用** break **。 <br/> <br/> [PS表格 - ForEach循环中使用BREAK的未处理例外](https://stackoverflow.com/questions/54331852/ps-forms-unhandled-exception-using-break-in-foreach-loop )

Stop-Pipeline.ps1
filter Stop-Pipeline {
  #requires -version 3
  # PS Bug: PS Forms - Unhandled Exception using BREAK in ForEach loop, https://stackoverflow.com/questions/54331852/ps-forms-unhandled-exception-using-break-in-foreach-loop
  $SteppablePipeline = { Select-Object -First 1 }.GetSteppablePipeline($MyInvocation.CommandOrigin)
  $SteppablePipeline.Begin($true)
  $SteppablePipeline.Process(0)
}

powershell 在domian中列出DC

List DC in domian
nltest /dclist:*Domain name*