Last active
October 8, 2021 18:09
-
-
Save SQLDBAWithABeard/9183c8d2c6493febdc831c22dce73d07 to your computer and use it in GitHub Desktop.
powershell vscode snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
/* | |
These are PowerShell snippets which you can use in Visual Studio Code | |
To use them click File --> Preferences --> User Snippets and type PowerShell | |
or edit $env:\appdata\code\user\snippets\powershell.json | |
In general and in order I converted exisitng snippets like this | |
Replace `$ with $$ | |
Replace \ with \\ | |
Replace " with \" | |
\r for new line | |
\t for tab | |
Each line in "" | |
, at the end of each line in the body except the last one | |
Look out for red or green squiggles :-) | |
*/ | |
"SMO-Server": { | |
"prefix": "SMO-Server", | |
"body": [ | |
"$$srv = New-Object Microsoft.SqlServer.Management.Smo.Server $$Server" | |
], | |
"description": "Creates a SQL Server SMO Object" | |
}, | |
"clixml": { | |
"prefix": "clixml", | |
"body": [ | |
"$$Credential | Export-CliXml -Path \"$${env:\\userprofile}\\NAME.Cred\"" | |
], | |
"description": "Creates a SQL Server SMO Object" | |
}, | |
"credential": { | |
"prefix": "credential", | |
"body": [ | |
"[pscredential]$$cred = New-Object System.Management.Automation.PSCredential ($$userName, $$secStringPassword)" | |
], | |
"description": "Creates a credential" | |
}, | |
"DataTable": { | |
"prefix": "DataTable", | |
"body": [ | |
"# Create DataTable Object", | |
"$$table = New-Object system.Data.DataTable $$TableName", | |
"\r# Create Columns", | |
"$$col1 = New-Object system.Data.DataColumn NAME1,([string])", | |
"$$col2 = New-Object system.Data.DataColumn NAME2,([decimal])", | |
"\r#Add the Columns to the table", | |
"$$table.columns.add($$col1)", | |
"$$table.columns.add($$col2)", | |
"\r# Create a new Row", | |
"$$row = $$table.NewRow() ", | |
"\r# Add values to new row", | |
"$$row.Name1 = 'VALUE'", | |
"$$row.NAME2 = 'VALUE'", | |
"\r#Add new row to table", | |
"$$table.Rows.Add($$row)" | |
], | |
"description": "Creates a Data Table Object" | |
}, | |
"Formatted Duration": { | |
"prefix": "Formatted Duration", | |
"body": [ | |
"$$FormattedDuration = @{", | |
"\tName = 'FormattedDuration'", | |
"\tExpression = {", | |
"\t\t[timespan]$$_.RunDuration.ToString().PadLeft(6,'0').insert(4,':').insert(2,':')", | |
"\t}", | |
"}" | |
], | |
"description": "Formats Get-SQLAgentJobHistory into timespan" | |
}, | |
"Prompt for input": { | |
"prefix": "Prompt for input", | |
"body": [ | |
"# Get some input from users ", | |
"$$title = \"Put your Title Here\" ", | |
"$$message = \"Put Your Message here (Y/N)\" ", | |
"$$yes = New-Object System.Management.Automation.Host.ChoiceDescription \"&Yes\", \"Will continue\" ", | |
"$$no = New-Object System.Management.Automation.Host.ChoiceDescription \"&No\", \"Will exit\" ", | |
"$$options = [System.Management.Automation.Host.ChoiceDescription[]]($$yes, $$no) ", | |
"$$result = $$host.ui.PromptForChoice($$title, $$message, $$options, 0) ", | |
"\r", | |
"if ($$result -eq 1) { ", | |
"\tWrite-Output \"User pressed no!\"", | |
"}", | |
"elseif ($$result -eq 0){ ", | |
"\tWrite-Output \"User pressed yes!\"", | |
"}" | |
], | |
"description": "Simple way of gathering input from users with simple yes and no" | |
}, | |
"Run SQL query with SMO": { | |
"prefix": "SQL query with SMO", | |
"body": [ | |
"$$srv = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $$Server", | |
"$$SqlConnection = $$srv.ConnectionContext", | |
"$$SqlConnection.StatementTimeout = 8000", | |
"$$SqlConnection.ConnectTimeout = 10", | |
"$$SqlConnection.Connect()", | |
"$$Results = $$SqlConnection.ExecuteWithResults($$Query).Tables", | |
"$$SqlConnection.Disconnect()" | |
], | |
"description": "creates SMO object and runs a sql command" | |
}, | |
"SQL Assemblies": { | |
"prefix": "SQL Assemblies", | |
"body": [ | |
"[void][reflection.assembly]::LoadWithPartialName( \"Microsoft.SqlServer.Management.Common\" );", | |
"[void][reflection.assembly]::LoadWithPartialName( \"Microsoft.SqlServer.SmoEnum\" );", | |
"[void][reflection.assembly]::LoadWithPartialName( \"Microsoft.SqlServer.Smo\" );", | |
"[void][reflection.assembly]::LoadWithPartialName( \"Microsoft.SqlServer.SmoExtended \" );", | |
"[void][System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SqlServer.ConnectionInfo\") " | |
], | |
"description": "Loads the SQL Assemblies" | |
}, | |
"Bulk copy from data table": { | |
"prefix": "Bulk copy from data table", | |
"body": [ | |
"$$sqlserver = ''", | |
"$$database = ''", | |
"$$table = ''", | |
"$$batchsize = 5000", | |
"\r", | |
"# Build the sqlbulkcopy connection, and set the timeout to infinite", | |
"$$connectionstring = \"Data Source=$$sqlserver;Integrated Security=true;Initial Catalog=$$database;\"", | |
"$$bulkcopy = New-Object Data.SqlClient.SqlBulkCopy($$connectionstring, [System.Data.SqlClient.SqlBulkCopyOptions]::TableLock)", | |
"$$bulkcopy.DestinationTableName = $$table", | |
"$$bulkcopy.bulkcopyTimeout = 0", | |
"$$bulkcopy.batchsize = $$batchsize", | |
"$$bulkcopy.WriteToServer($$datatable)", | |
"$$datatable.Clear()" | |
], | |
"description": "Bulk copy from data table" | |
}, | |
"WSMan Test and CIM instead of WMI": { | |
"prefix": "WSMan Test and CIM instead of WMI", | |
"body": [ | |
"## Servername", | |
"$$Server = ''", | |
"\r", | |
"## Test for WSMan", | |
"$$WSMAN = Test-WSMan $$Server", | |
"\r", | |
"## Change Protocol if needed for CimSession", | |
"if($$WSMAN.ProductVersion.Contains('Stack: 2.0')) {", | |
"\t$$opt = New-CimSessionOption -Protocol Dcom", | |
"\t$$s = New-CimSession -ComputerName $$Server -SessionOption $$opt", | |
"}", | |
"else {", | |
"\t$$s = New-CimSession -ComputerName $$Server", | |
"}", | |
"\r", | |
"## Do your funky CIM stuff", | |
"Get-CimInstance -ClassName Win32_OperatingSystem -CimSession $$s| select LastBootUpTime " | |
], | |
"description": "Creates a CiM Session depending on the results of the WSMan test" | |
}, | |
"Max Length of Datatable": { | |
"prefix": "Max Length of Datatable", | |
"body": [ | |
"$$columns = ($$datatable | Get-Member -MemberType Property).Name", | |
"foreach($$column in $$Columns) {", | |
" $$max = 0", | |
" foreach ($$a in $$datatable){", | |
" if($$max -lt $$a.$$column.length){", | |
" $$max = $$a.$$column.length", | |
" }", | |
" }", | |
" Write-Output \"$$column max length is $$max\"", | |
"}" | |
], | |
"description": "Takes a datatable object and iterates through it to get the max length of the string columns - useful for data loads" | |
}, | |
"stopWatch": { | |
"prefix": "Stopwatch", | |
"body": [ | |
"$$sw = [diagnostics.stopwatch]::StartNew()" | |
], | |
"description": "Starts a stopwatch" | |
}, | |
"New Excel Object": { | |
"prefix": "Excel Object", | |
"body": [ | |
"# Create a .com object for Excel", | |
"$$xl = new-object -comobject excel.application", | |
"$$xl.Visible = $$true # Set this to False when you run in production", | |
"$$wb = $$xl.Workbooks.Add() # Add a workbook ", | |
"$$ws = $$wb.Worksheets.Item(1) # Add a worksheet", | |
"$$cells=$$ws.Cells", | |
"\r ", | |
"Do Some Stuff", | |
"\r ", | |
"perhaps", | |
"\r ", | |
"$$cells.item($$row,$$col)=\"Server\"", | |
"$$cells.item($$row,$$col).font.size=16", | |
"$$Cells.item($$row,$$col).Columnwidth = 10", | |
"$$col++", | |
"\r", | |
"$$wb.Saveas(\"C:\\temp\\Test$$filename.xlsx\")", | |
"$$xl.quit()" | |
], | |
"description": "Creates a New Excel Object" | |
}, | |
"SQL Authentication SMO": { | |
"prefix": "SQL Authentication SMO", | |
"body": [ | |
"$$sqllogin = Get-Credential ", | |
"$$srv = New-Object Microsoft.SqlServer.Management.Smo.Server $$server", | |
"$$srv.ConnectionContext.LoginSecure = $$false", | |
"$$srv.ConnectionContext.set_Login($$sqllogin.username)", | |
"$$srv.ConnectionContext.set_SecurePassword($$sqllogin.Password)", | |
"\r", | |
"try { ", | |
"\t$$srv.ConnectionContext.Connect() ", | |
"} ", | |
"catch { ", | |
"\tthrow \"Can't connect to $$server or access denied. Quitting.\" ", | |
"}" | |
], | |
"description": "Creates a SQL Authentication SMO Server Object" | |
}, | |
"Simple Create Database": { | |
"prefix": "Database - Create with SMO", | |
"body": [ | |
"##Create a database", | |
"$$server = ''", | |
"$$DBName = 'TheBeardsDatabase'", | |
"$$db = New-Object Microsoft.SqlServer.Management.Smo.Database $$Server, $$DBName", | |
"$$db.Create()" | |
], | |
"description": "Create Database using SMO and defaults" | |
}, | |
"Create a database Role": { | |
"prefix": "Role - Database Create with SMO", | |
"body": [ | |
"##Create a role", | |
"$$server = ''", | |
"$$DBName = ''", | |
"$$RoleName = ''", | |
"$$srv = New-Object Microsoft.SqlServer.Management.Smo.Server $$Server", | |
"$$db = $$srv.Databases[$$DBName]", | |
"$$Role = New-Object Microsoft.SqlServer.Management.Smo.DatabaseRole $$db, $$RoleName", | |
"$$Role.Create()" | |
], | |
"description": "Simple SMO to create a Database Role" | |
}, | |
"SQL firewall Rules": { | |
"prefix": "Firewall Rules SQL", | |
"body": [ | |
"#Enabling SQL Server Ports", | |
"New-NetFirewallRule -DisplayName “SQL Server” -Direction Inbound –Protocol TCP –LocalPort 1433 -Action allow", | |
"New-NetFirewallRule -DisplayName “SQL Admin Connection” -Direction Inbound –Protocol TCP –LocalPort 1434 -Action allow", | |
"New-NetFirewallRule -DisplayName “SQL Database Management” -Direction Inbound –Protocol UDP –LocalPort 1434 -Action allow", | |
"New-NetFirewallRule -DisplayName “SQL Service Broker” -Direction Inbound –Protocol TCP –LocalPort 4022 -Action allow", | |
"New-NetFirewallRule -DisplayName “SQL Debugger/RPC” -Direction Inbound –Protocol TCP –LocalPort 135 -Action allow", | |
"#Enabling SQL Analysis Ports", | |
"New-NetFirewallRule -DisplayName “SQL Analysis Services” -Direction Inbound –Protocol TCP –LocalPort 2383 -Action allow", | |
"New-NetFirewallRule -DisplayName “SQL Browser” -Direction Inbound –Protocol TCP –LocalPort 2382 -Action allow", | |
"#Enabling Misc. Applications", | |
"New-NetFirewallRule -DisplayName “HTTP” -Direction Inbound –Protocol TCP –LocalPort 80 -Action allow", | |
"New-NetFirewallRule -DisplayName “SSL” -Direction Inbound –Protocol TCP –LocalPort 443 -Action allow", | |
"New-NetFirewallRule -DisplayName “SQL Server Browse Button Service” -Direction Inbound –Protocol UDP –LocalPort 1433 -Action allow" | |
], | |
"description": "Set Firewall for SQL " | |
}, | |
"Remote Management firewall Rules": { | |
"prefix": "Firewall Rules Remote - File and Printer", | |
"body": [ | |
"Set-NetFirewallRule -DisplayGroup 'File And Printer Sharing' -Enabled True" | |
], | |
"description": "Set Firewal for Remote Mangememnt WMI etc" | |
}, | |
"Ping firewall Rules": { | |
"prefix": "Firewall Rules Ping", | |
"body": [ | |
"New-NetFirewallRule -Name Allow_Ping -Description 'Allow Ping' -Protocol ICMPv4 -Icmptype 8 -Enabled True -Profile Any -Action Allow" | |
], | |
"description": "Set Firewall for ping" | |
}, | |
"Remote Management firewall Rules ": { | |
"prefix": "Firewall Rules Remote - wmi", | |
"body": [ | |
"Get-NetFirewallRule -DisplayGroup 'Remote*' | Set-NetFirewallRule -Enabled True" | |
], | |
"description": "Set Firewall for Remote Management" | |
}, | |
"Show All Excel Colours": { | |
"prefix": "Excel Colours", | |
"body": [ | |
"$$xl = New-Object -ComObject Excel.Application", | |
"$$xl.Visible = $$true", | |
"$$xl.DisplayAlerts = $$False", | |
"$$wkbk = $$xl.WorkBooks.Add()", | |
"$$sheet = $$wkbk.WorkSheets.Item(1)", | |
"$$xl.Visible = $$true", | |
"for($$i=1; $$i -le 56; $$i++) {", | |
"switch ($$i) {", | |
"{$$_ -le 14} {$$row = $$i; $$col = 1}", | |
"{$$_ -ge 15 -and $$_ -le 28} {$$row = $$i–14; $$col = 3}", | |
"{$$_ -ge 29 -and $$_ -le 42} {$$row = $$i–28; $$col = 5}", | |
"{$$_ -ge 43 -and $$_ -le 56} {$$row = $$i–42; $$col = 7}", | |
"}", | |
"$$sheet.Cells.Item($$row, $$col).FormulaLocal = $$i", | |
"$$sheet.Cells.Item($$row, $$col+1).Interior.ColorIndex = $$i", | |
"}", | |
"", | |
"# $$xl.Quit()" | |
], | |
"description": "Shows all the colour indexes for the Excel colours" | |
}, | |
"IfShouldProcess": { | |
"prefix": "IfShouldProcess", | |
"body": [ | |
"if ($$PSCmdlet.ShouldProcess(\"${1:The Item}\" , \"${2:The Change}\")) {", | |
" # ${1:The Item}", | |
"}" | |
], | |
"description": "Creates an if should process" | |
}, | |
"AssertMock": { | |
"prefix": "AssertMock", | |
"body": [ | |
"$$assertMockParams = @{", | |
"'CommandName' = '${1:FunctionName}'", | |
"'Times' = 2", | |
"'Exactly' = $$true", | |
"}", | |
"{Assert-MockCalled @assertMockParams} | Should -Not -Throw -Because \"${2:Because}\" " | |
], | |
"description": "AssertMock snippet for Pestering" | |
}, | |
"Pester for Parameter": { | |
"prefix": "Param Pester", | |
"body": [ | |
"It \"${1:FunctionName} Should have a parameter ${2:ParameterName}\" {", | |
" (Get-Command ${1:FunctionName}).Parameters['${2:ParameterName}'].Count | Should -Be 1", | |
"}" | |
], | |
"description": "Pester Test for Parameter" | |
}, | |
"Network Connection To Private": { | |
"prefix": "PrivateNetworkConnections", | |
"body": [ | |
"(Get-NetConnectionProfile).Where{", | |
"$$_.NetworkCategory -ne 'Private'", | |
"}.ForEach{", | |
"Set-NetConnectionProfile -Name $$PsItem.Name -NetworkCategory Private", | |
"}" | |
], | |
"description": "Sets all network connections to Private" | |
}, | |
"Pester for Mandatory Pester": { | |
"prefix": "mandatoryParamPester", | |
"body": [ | |
"It \"${1:FunctionName} Should have a mandatory parameter ${2:ParameterName}\" {", | |
" (Get-Command ${1:FunctionName}).Parameters['${2:ParameterName}'].Attributes.Mandatory | Should be $true", | |
"}" | |
], | |
"description": "Pester Test for Parameter" | |
}, | |
"Sync Fork": { | |
"prefix": "sync github fork", | |
"body": [ | |
"Git status", | |
"git fetch upstream", | |
"Git checkout master", | |
"git merge upstream/master" | |
], | |
"description": "Because I never remember how to sync a fork!" | |
}, | |
"Parameter Pester Test": { | |
"prefix": "Param Pester Test", | |
"body": [ | |
"$$MandatoryParameters = '${2:ParamName}', '${3:ParamName}'", | |
"$$MandatoryParameters.ForEach{", | |
" It \"${1:FunctionName} Should have a mandatory parameter $$psitem\" {", | |
" (Get-Command ${1:FunctionName} ).Parameters[$$psitem].Attributes.Mandatory | Should be $$true", | |
" }", | |
"}", | |
"$$Parameters = '${2:ParamName}','${3:ParamName}'", | |
"$$Parameters.ForEach{", | |
" It \"${1:FunctionName} Should have a mandatory parameter $$psitem\" {", | |
" (Get-Command ${1:FunctionName} ).Parameters[$$psitem].Count | Should be 1", | |
" }", | |
"}" | |
], | |
"description": "Better Pester mandatory and parameter tests" | |
}, | |
"Create Resource Group": { | |
"prefix": "azure resource group", | |
"body": [ | |
"$$RGName = '${1:Resource Group Name}'", | |
"$$Location = '${2:Location}'", | |
"$$Tags = @{", | |
"Owner = '${3:OwnerTag}'", | |
"ProjectName ='${4:ProjectTag}'", | |
"}", | |
"# create resource group if it doesnt exist", | |
"if(-not (Get-AzResourceGroup -Name $$RGName -ErrorAction SilentlyContinue)){", | |
"Write-Output 'Creating Resource Group $$RGName'", | |
"New-AzResourceGroup -Name $$RGName -Location $$Location -Tag $$Tags", | |
"}else {", | |
"Write-Output 'Resource Group $RGName Exists'", | |
"," | |
], | |
"description": "create azure resource group" | |
}, | |
"Run This File as Admin": { | |
"prefix": "admin run file full", | |
"body": [ | |
"#region Run As Admin", | |
"$$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())", | |
"if ($$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {", | |
"Write-Verbose \"Process is running as Admin\"", | |
"}", | |
"else {", | |
"# Get some input from users ", | |
"$$title = \"Want to try and run as admin ?\" ", | |
"$$message = \"Want to try and run as admin ? (Y/N)\" ", | |
"$$yes = New-Object System.Management.Automation.Host.ChoiceDescription \"&Yes\", \"Will continue\" ", | |
"$$no = New-Object System.Management.Automation.Host.ChoiceDescription \"&No\", \"Will exit\" ", | |
"$$options = [System.Management.Automation.Host.ChoiceDescription[]]($$yes, $$no) ", | |
"$$result = $$host.ui.PromptForChoice($$title, $$message, $$options, 0) ", | |
"if ($$result -eq 1) { ", | |
"Write-Warning \"Nope - You can't carry on. This needs to run as an administrative process. Right Click and run as admin please\"", | |
" Break", | |
"}", | |
"elseif ($$result -eq 0) { ", | |
"$$MyInvocation.MyCommand.Definition ", | |
"Start-Process powershell.exe \"-NoExit -File\", ('\"{0}\"' -f $$MyInvocation.MyCommand.Path) -Verb RunAs ", | |
"Break", | |
"}", | |
"}", | |
"#endregion" | |
], | |
"description": "Check if process is runnign as admin and if not run it as admin with a prompt" | |
}, | |
"Run This Command as Admin Full": { | |
"prefix": "admin run command full", | |
"body": [ | |
"$$Command = { Write-Warning 'This is a Warning' }", | |
"#region Run As Admin", | |
"$$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())", | |
"if ($$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {", | |
"Write-Verbose \"Process is running as Admin\"", | |
"}", | |
"else {", | |
"# Get some input from users ", | |
"$$title = \"Want to try and run as admin ?\" ", | |
"$$message = \"Want to try and run as admin ? (Y/N)\" ", | |
"$$yes = New-Object System.Management.Automation.Host.ChoiceDescription \"&Yes\", \"Will continue\" ", | |
"$$no = New-Object System.Management.Automation.Host.ChoiceDescription \"&No\", \"Will exit\" ", | |
"$$options = [System.Management.Automation.Host.ChoiceDescription[]]($$yes, $$no) ", | |
"$$result = $$host.ui.PromptForChoice($$title, $$message, $$options, 0) ", | |
"if ($$result -eq 1) { ", | |
"Write-Warning \"Nope - You can't carry on. This needs to run as an administrative process. Right Click and run as admin please\"", | |
" Break", | |
"}", | |
"elseif ($$result -eq 0) { ", | |
"Start-Process powershell.exe -ArgumentList \"-NoExit -noprofile -Command & {$$Command}\" -Verb RunAs ", | |
"Break", | |
"}", | |
"}", | |
"#endregion" | |
], | |
"description": "Check if process is running as admin and if not run the specified command as admin with a prompt" | |
}, | |
"Run Command as Admin Simple PowerShell": { | |
"prefix": "admin run command simple powershell", | |
"body": [ | |
"$$Command = { Write-Warning 'This is a Warning' }", | |
"Start-Process powershell.exe -ArgumentList \"-NoExit -noprofile -Command & {$$Command}\" -Verb RunAs " | |
], | |
"description": "run command as admin using PowerShell" | |
}, | |
"Run Command as Admin Simple pwsh": { | |
"prefix": "admin run command simple pwsh", | |
"body": [ | |
"$$Command = { Write-Warning 'This is a Warning' }", | |
"Start-Process pwsh.exe -ArgumentList \"-NoExit -noprofile -Command & {$$Command}\" -Verb RunAs " | |
], | |
"description": "run command as admin using pwsh" | |
}, | |
"Download File NET": { | |
"prefix": "download a file with .net", | |
"body": [ | |
"$$Url = ''", | |
"$$OutputFile = ''", | |
"$$StartTime = Get-Date", | |
"", | |
"$$wc = New-Object System.Net.WebClient", | |
"$$wc.DownloadFile($$Url, $$OutputFile)", | |
"", | |
"Write-Output \"Time taken: $((Get-Date).Subtract($$StartTime).Seconds) second(s)\"" | |
], | |
"description": "Downlaods a file with .NET" | |
}, | |
"Download File IWR": { | |
"prefix": "download a file with Invoke-WebRequest", | |
"body": [ | |
"$$Url = ''", | |
"$$OutputFile = ''", | |
"$$StartTime = Get-Date", | |
"", | |
"Invoke-WebRequest -Uri $$Url -OutFile $$OutputFile", | |
"Write-Output \"Time taken: $((Get-Date).Subtract($$StartTime).Seconds) second(s)\"" | |
], | |
"description": "Downlaods a file with Invoke-WebRequest" | |
}, | |
"Alter Service Account - PowerShell 5": { | |
"prefix": "Change a service account ", | |
"body": [ | |
"$$UserAccount = '${1:UserAccount}'", | |
"$$Password = '${2:Password}'", | |
"", | |
"$$service = Get-CimInstance -ComputerName ${3:ComputerName} -ClassName win32_service -Filter \"name='${4:Filter}'\" ", | |
"$$service | Invoke-CimMethod -MethodName Change -Arguments @{StartName=$$UserAccount;StartPassword=$$Password} ", | |
], | |
"description": "Changes a service account with PowerShell 5" | |
}, | |
"Alter Service Account and restart - PowerShell 5": { | |
"prefix": "Change a service account and restart", | |
"body": [ | |
"$$UserAccount = '${1:UserAccount}'", | |
"$$Password = '${2:Password}'", | |
"$$SqlInstance = '${3:SQLInstance}'", | |
"$$ComputerName,$$InstanceName = $$SQLinstance.Split('\\')", | |
"if($$null -eq $$InstanceName){", | |
" $$EngineService = 'MSSQLSERVER'", | |
" $$AgentService = 'SQLSERVERAGENT'", | |
"} else{", | |
" $$EngineService = 'MSSQL' + '$' + $$InstanceName", | |
" $$AgentService = 'SQLAgent' + '$' + $$InstanceName", | |
"}", | |
"", | |
"$$service = Get-CimInstance -ComputerName $$ComputerName -ClassName win32_service -Filter \"name='$$AgentService'\" ", | |
"$$service | Invoke-CimMethod -MethodName Change -Arguments @{StartName=$$UserAccount;StartPassword=$$Password} ", | |
"$$service | Invoke-CimMethod -MethodName Change -Arguments @{StartMode='Automatic'} ", | |
"", | |
"$$service = Get-CimInstance -ComputerName $$ComputerName -ClassName win32_service -Filter \"name='$$EngineService'\" ", | |
"$$service | Invoke-CimMethod -MethodName Change -Arguments @{StartName=$$UserAccount;StartPassword=$$Password} ", | |
"", | |
"Enter-PSSession $$ComputerName", | |
"Get-Service -Name $$EngineService | Stop-Service -Force", | |
"Get-Service -Name $$EngineService | Start-Service", | |
"Get-Service -Name $$AgentService | Stop-Service -Force", | |
"Get-Service -Name $$AgentService | Start-Service ", | |
"Exit" | |
], | |
"description": "Changes a service account with PowerShell 5" | |
}, | |
"Get Azure VM Image": { | |
"prefix": "Azure VM Image", | |
"body": [ | |
"$$location = '${1:enter location like northeurope}'", | |
"$$PSDefaultParameterValues = @{", | |
" \"*-az*:location\" = $$location", | |
"}", | |
"$$Publisher = (Get-AzVMImagePublisher | Select PublisherName | ogv -PassThru).PublisherName", | |
"", | |
"$$PSDefaultParameterValues.Add(\"*-az*:PublisherName\", $$Publisher)", | |
"$$Offer = (Get-AzVMImageOffer | Select Offer | ogv -PassThru).Offer", | |
"", | |
"$$PSDefaultParameterValues.Add(\"*-az*:Offer\", $$Offer)", | |
"", | |
"$$sku = (Get-AzVMImageSku | Select Skus | ogv -PassThru).Skus", | |
"", | |
"$$PSDefaultParameterValues.Add(\"*-az*:Skus\", \"$$sku\")", | |
"Get-AzVMImage " | |
], | |
"description": "Get Azure VM Image" | |
} | |
} | |
/* | |
// Place your snippets for PowerShell here. Each snippet is defined under a snippet name and has a prefix, body and | |
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: | |
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the | |
// same ids are connected. | |
// Example: | |
"Print to console": { | |
"prefix": "log", | |
"body": [ | |
"console.log('$1');", | |
"$2" | |
], | |
"description": "Log output to console" | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment