Skip to content

Commit 4a277fb

Browse files
committed
[pwsh]Add code snippets.
1 parent 4f46855 commit 4a277fb

File tree

2 files changed

+74
-2
lines changed

2 files changed

+74
-2
lines changed

PowerShell/snippets.ps1

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Copyright (c) 2023 Matthias Wolf, Mawosoft.
2+
3+
<#
4+
.SYNOPSIS
5+
Code snippets for Powershell.
6+
.DESCRIPTION
7+
Defines code snippets for PowerShell and outputs them as a JSON string for use in
8+
a VSCode code snippets file.
9+
.OUTPUTS
10+
[string] JSON string for use in a VSCode code snippets file.
11+
.NOTES
12+
- The 'body' property can be a [scriptblock] to allow syntax checking.
13+
- However, when using template variables, 'body' must be a string.
14+
Using a single here-string is fine (no need for those silly line arrays).
15+
.LINK
16+
https://code.visualstudio.com/docs/editor/userdefinedsnippets
17+
#>
18+
19+
[CmdletBinding()]
20+
[OutputType([string])]
21+
param()
22+
23+
@{
24+
'no-dotsourcing' = @{
25+
prefix = 'no-dotsourcing'
26+
description = 'Prevent global dot-sourcing of a script.'
27+
body = {
28+
try {
29+
$null = Get-Variable 'foobar' -Scope 1 -ErrorAction Stop
30+
}
31+
catch [System.ArgumentOutOfRangeException] {
32+
throw 'Dot-sourcing this script is not allowed.'
33+
}
34+
catch {}
35+
}
36+
}
37+
38+
'dynamic-assemblies' = @{
39+
prefix = 'dynamic-assemblies'
40+
description = 'Get the assemblies with dynamically created types.'
41+
body = {
42+
[System.AppDomain]::CurrentDomain.GetAssemblies().Where({ $_.IsDynamic -or $_.GetName().Version -eq '0.0.0.0' })
43+
}
44+
}
45+
46+
'dynamic-types' = @{
47+
prefix = 'dynamic-types'
48+
description = 'Get the dynamically created types and their assemblies.'
49+
body = {
50+
[System.AppDomain]::CurrentDomain.GetAssemblies().Where({
51+
$_.IsDynamic -or $_.GetName().Version -eq '0.0.0.0'
52+
}) | Select-Object FullName, ExportedTypes
53+
}
54+
}
55+
56+
57+
} | ForEach-Object {
58+
$_.GetEnumerator().ForEach({
59+
if ($_.Value.body -is [scriptblock]) {
60+
$_.Value.body = ([string]$_.Value.body).Trim().Replace('$', '\$') -csplit '\r?\n'
61+
}
62+
else {
63+
$_.Value.body = ([string]$_.Value.body).Trim() -csplit '\r?\n'
64+
}
65+
})
66+
$_
67+
} | ConvertTo-Json

README.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,13 @@
22

33
Miscellaneous scripts.
44

5-
- **PowerShell/Profile**\
6-
Creates a PowerShell profile script with automatic customizations based on installed software.
5+
- **PowerShell**
6+
7+
- **Profile**\
8+
Creates a PowerShell profile script with automatic customizations based on installed software.
9+
10+
- **snippets.ps1**\
11+
Code snippets for PowerShell.
712

813
- **VirtualBox**\
914
Batch scripts to automatically take a snapshot before starting a VM and verify snapshot creation inside the VM.

0 commit comments

Comments
 (0)