├── .gitignore ├── LICENSE ├── README.MD ├── ScriptFeedbackProvider.sln ├── Source ├── Commands │ ├── GetScriptFeedbackProviderCommand.cs │ ├── RegisterScriptFeedbackProviderCommand.cs │ └── UnregisterScriptFeedbackProviderCommand.cs ├── FeedbackProvider.cs ├── ScriptFeedbackProvider.csproj ├── ScriptFeedbackProvider.psd1 └── packages.lock.json └── images └── README ├── image-1.png ├── image-2.png └── image.png /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from `dotnet new gitignore` 5 | 6 | # dotenv files 7 | .env 8 | 9 | # User-specific files 10 | *.rsuser 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Mono auto generated files 20 | mono_crash.* 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | [Dd]ebugPublic/ 25 | [Rr]elease/ 26 | [Rr]eleases/ 27 | x64/ 28 | x86/ 29 | [Ww][Ii][Nn]32/ 30 | [Aa][Rr][Mm]/ 31 | [Aa][Rr][Mm]64/ 32 | bld/ 33 | [Bb]in/ 34 | [Oo]bj/ 35 | [Ll]og/ 36 | [Ll]ogs/ 37 | 38 | # Visual Studio 2015/2017 cache/options directory 39 | .vs/ 40 | # Uncomment if you have tasks that create the project's static files in wwwroot 41 | #wwwroot/ 42 | 43 | # Visual Studio 2017 auto generated files 44 | Generated\ Files/ 45 | 46 | # MSTest test Results 47 | [Tt]est[Rr]esult*/ 48 | [Bb]uild[Ll]og.* 49 | 50 | # NUnit 51 | *.VisualState.xml 52 | TestResult.xml 53 | nunit-*.xml 54 | 55 | # Build Results of an ATL Project 56 | [Dd]ebugPS/ 57 | [Rr]eleasePS/ 58 | dlldata.c 59 | 60 | # Benchmark Results 61 | BenchmarkDotNet.Artifacts/ 62 | 63 | # .NET 64 | project.lock.json 65 | project.fragment.lock.json 66 | artifacts/ 67 | 68 | # Tye 69 | .tye/ 70 | 71 | # ASP.NET Scaffolding 72 | ScaffoldingReadMe.txt 73 | 74 | # StyleCop 75 | StyleCopReport.xml 76 | 77 | # Files built by Visual Studio 78 | *_i.c 79 | *_p.c 80 | *_h.h 81 | *.ilk 82 | *.meta 83 | *.obj 84 | *.iobj 85 | *.pch 86 | *.pdb 87 | *.ipdb 88 | *.pgc 89 | *.pgd 90 | *.rsp 91 | *.sbr 92 | *.tlb 93 | *.tli 94 | *.tlh 95 | *.tmp 96 | *.tmp_proj 97 | *_wpftmp.csproj 98 | *.log 99 | *.tlog 100 | *.vspscc 101 | *.vssscc 102 | .builds 103 | *.pidb 104 | *.svclog 105 | *.scc 106 | 107 | # Chutzpah Test files 108 | _Chutzpah* 109 | 110 | # Visual C++ cache files 111 | ipch/ 112 | *.aps 113 | *.ncb 114 | *.opendb 115 | *.opensdf 116 | *.sdf 117 | *.cachefile 118 | *.VC.db 119 | *.VC.VC.opendb 120 | 121 | # Visual Studio profiler 122 | *.psess 123 | *.vsp 124 | *.vspx 125 | *.sap 126 | 127 | # Visual Studio Trace Files 128 | *.e2e 129 | 130 | # TFS 2012 Local Workspace 131 | $tf/ 132 | 133 | # Guidance Automation Toolkit 134 | *.gpState 135 | 136 | # ReSharper is a .NET coding add-in 137 | _ReSharper*/ 138 | *.[Rr]e[Ss]harper 139 | *.DotSettings.user 140 | 141 | # TeamCity is a build add-in 142 | _TeamCity* 143 | 144 | # DotCover is a Code Coverage Tool 145 | *.dotCover 146 | 147 | # AxoCover is a Code Coverage Tool 148 | .axoCover/* 149 | !.axoCover/settings.json 150 | 151 | # Coverlet is a free, cross platform Code Coverage Tool 152 | coverage*.json 153 | coverage*.xml 154 | coverage*.info 155 | 156 | # Visual Studio code coverage results 157 | *.coverage 158 | *.coveragexml 159 | 160 | # NCrunch 161 | _NCrunch_* 162 | .*crunch*.local.xml 163 | nCrunchTemp_* 164 | 165 | # MightyMoose 166 | *.mm.* 167 | AutoTest.Net/ 168 | 169 | # Web workbench (sass) 170 | .sass-cache/ 171 | 172 | # Installshield output folder 173 | [Ee]xpress/ 174 | 175 | # DocProject is a documentation generator add-in 176 | DocProject/buildhelp/ 177 | DocProject/Help/*.HxT 178 | DocProject/Help/*.HxC 179 | DocProject/Help/*.hhc 180 | DocProject/Help/*.hhk 181 | DocProject/Help/*.hhp 182 | DocProject/Help/Html2 183 | DocProject/Help/html 184 | 185 | # Click-Once directory 186 | publish/ 187 | 188 | # Publish Web Output 189 | *.[Pp]ublish.xml 190 | *.azurePubxml 191 | # Note: Comment the next line if you want to checkin your web deploy settings, 192 | # but database connection strings (with potential passwords) will be unencrypted 193 | *.pubxml 194 | *.publishproj 195 | 196 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 197 | # checkin your Azure Web App publish settings, but sensitive information contained 198 | # in these scripts will be unencrypted 199 | PublishScripts/ 200 | 201 | # NuGet Packages 202 | *.nupkg 203 | # NuGet Symbol Packages 204 | *.snupkg 205 | # The packages folder can be ignored because of Package Restore 206 | **/[Pp]ackages/* 207 | # except build/, which is used as an MSBuild target. 208 | !**/[Pp]ackages/build/ 209 | # Uncomment if necessary however generally it will be regenerated when needed 210 | #!**/[Pp]ackages/repositories.config 211 | # NuGet v3's project.json files produces more ignorable files 212 | *.nuget.props 213 | *.nuget.targets 214 | 215 | # Microsoft Azure Build Output 216 | csx/ 217 | *.build.csdef 218 | 219 | # Microsoft Azure Emulator 220 | ecf/ 221 | rcf/ 222 | 223 | # Windows Store app package directories and files 224 | AppPackages/ 225 | BundleArtifacts/ 226 | Package.StoreAssociation.xml 227 | _pkginfo.txt 228 | *.appx 229 | *.appxbundle 230 | *.appxupload 231 | 232 | # Visual Studio cache files 233 | # files ending in .cache can be ignored 234 | *.[Cc]ache 235 | # but keep track of directories ending in .cache 236 | !?*.[Cc]ache/ 237 | 238 | # Others 239 | ClientBin/ 240 | ~$* 241 | *~ 242 | *.dbmdl 243 | *.dbproj.schemaview 244 | *.jfm 245 | *.pfx 246 | *.publishsettings 247 | orleans.codegen.cs 248 | 249 | # Including strong name files can present a security risk 250 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 251 | #*.snk 252 | 253 | # Since there are multiple workflows, uncomment next line to ignore bower_components 254 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 255 | #bower_components/ 256 | 257 | # RIA/Silverlight projects 258 | Generated_Code/ 259 | 260 | # Backup & report files from converting an old project file 261 | # to a newer Visual Studio version. Backup files are not needed, 262 | # because we have git ;-) 263 | _UpgradeReport_Files/ 264 | Backup*/ 265 | UpgradeLog*.XML 266 | UpgradeLog*.htm 267 | ServiceFabricBackup/ 268 | *.rptproj.bak 269 | 270 | # SQL Server files 271 | *.mdf 272 | *.ldf 273 | *.ndf 274 | 275 | # Business Intelligence projects 276 | *.rdl.data 277 | *.bim.layout 278 | *.bim_*.settings 279 | *.rptproj.rsuser 280 | *- [Bb]ackup.rdl 281 | *- [Bb]ackup ([0-9]).rdl 282 | *- [Bb]ackup ([0-9][0-9]).rdl 283 | 284 | # Microsoft Fakes 285 | FakesAssemblies/ 286 | 287 | # GhostDoc plugin setting file 288 | *.GhostDoc.xml 289 | 290 | # Node.js Tools for Visual Studio 291 | .ntvs_analysis.dat 292 | node_modules/ 293 | 294 | # Visual Studio 6 build log 295 | *.plg 296 | 297 | # Visual Studio 6 workspace options file 298 | *.opt 299 | 300 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 301 | *.vbw 302 | 303 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 304 | *.vbp 305 | 306 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 307 | *.dsw 308 | *.dsp 309 | 310 | # Visual Studio 6 technical files 311 | *.ncb 312 | *.aps 313 | 314 | # Visual Studio LightSwitch build output 315 | **/*.HTMLClient/GeneratedArtifacts 316 | **/*.DesktopClient/GeneratedArtifacts 317 | **/*.DesktopClient/ModelManifest.xml 318 | **/*.Server/GeneratedArtifacts 319 | **/*.Server/ModelManifest.xml 320 | _Pvt_Extensions 321 | 322 | # Paket dependency manager 323 | .paket/paket.exe 324 | paket-files/ 325 | 326 | # FAKE - F# Make 327 | .fake/ 328 | 329 | # CodeRush personal settings 330 | .cr/personal 331 | 332 | # Python Tools for Visual Studio (PTVS) 333 | __pycache__/ 334 | *.pyc 335 | 336 | # Cake - Uncomment if you are using it 337 | # tools/** 338 | # !tools/packages.config 339 | 340 | # Tabs Studio 341 | *.tss 342 | 343 | # Telerik's JustMock configuration file 344 | *.jmconfig 345 | 346 | # BizTalk build output 347 | *.btp.cs 348 | *.btm.cs 349 | *.odx.cs 350 | *.xsd.cs 351 | 352 | # OpenCover UI analysis results 353 | OpenCover/ 354 | 355 | # Azure Stream Analytics local run output 356 | ASALocalRun/ 357 | 358 | # MSBuild Binary and Structured Log 359 | *.binlog 360 | 361 | # NVidia Nsight GPU debugger configuration file 362 | *.nvuser 363 | 364 | # MFractors (Xamarin productivity tool) working folder 365 | .mfractor/ 366 | 367 | # Local History for Visual Studio 368 | .localhistory/ 369 | 370 | # Visual Studio History (VSHistory) files 371 | .vshistory/ 372 | 373 | # BeatPulse healthcheck temp database 374 | healthchecksdb 375 | 376 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 377 | MigrationBackup/ 378 | 379 | # Ionide (cross platform F# VS Code tools) working folder 380 | .ionide/ 381 | 382 | # Fody - auto-generated XML schema 383 | FodyWeavers.xsd 384 | 385 | # VS Code files for those working on multiple tools 386 | .vscode/* 387 | !.vscode/settings.json 388 | !.vscode/tasks.json 389 | !.vscode/launch.json 390 | !.vscode/extensions.json 391 | *.code-workspace 392 | 393 | # Local History for Visual Studio Code 394 | .history/ 395 | 396 | # Windows Installer files from build outputs 397 | *.cab 398 | *.msi 399 | *.msix 400 | *.msm 401 | *.msp 402 | 403 | # JetBrains Rider 404 | *.sln.iml 405 | .idea 406 | 407 | ## 408 | ## Visual studio for Mac 409 | ## 410 | 411 | 412 | # globs 413 | Makefile.in 414 | *.userprefs 415 | *.usertasks 416 | config.make 417 | config.status 418 | aclocal.m4 419 | install-sh 420 | autom4te.cache/ 421 | *.tar.gz 422 | tarballs/ 423 | test-results/ 424 | 425 | # Mac bundle stuff 426 | *.dmg 427 | *.app 428 | 429 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 430 | # General 431 | .DS_Store 432 | .AppleDouble 433 | .LSOverride 434 | 435 | # Icon must end with two \r 436 | Icon 437 | 438 | 439 | # Thumbnails 440 | ._* 441 | 442 | # Files that might appear in the root of a volume 443 | .DocumentRevisions-V100 444 | .fseventsd 445 | .Spotlight-V100 446 | .TemporaryItems 447 | .Trashes 448 | .VolumeIcon.icns 449 | .com.apple.timemachine.donotpresent 450 | 451 | # Directories potentially created on remote AFP share 452 | .AppleDB 453 | .AppleDesktop 454 | Network Trash Folder 455 | Temporary Items 456 | .apdisk 457 | 458 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 459 | # Windows thumbnail cache files 460 | Thumbs.db 461 | ehthumbs.db 462 | ehthumbs_vista.db 463 | 464 | # Dump file 465 | *.stackdump 466 | 467 | # Folder config file 468 | [Dd]esktop.ini 469 | 470 | # Recycle Bin used on file shares 471 | $RECYCLE.BIN/ 472 | 473 | # Windows Installer files 474 | *.cab 475 | *.msi 476 | *.msix 477 | *.msm 478 | *.msp 479 | 480 | # Windows shortcuts 481 | *.lnk 482 | 483 | # Vim temporary swap files 484 | *.swp 485 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Copyright 2023 Justin Grote @JustinWGrote github.com/JustinGrote 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | # PowerShell Script Based Feedback Providers 2 | 3 | This module allows you to write feedback providers in PowerShell rather than C# and register them. 4 | 5 | By default, feedback providers are registered for errors only. To register for another type, use the `-Trigger` parameter. 6 | 7 | Also errors and potential issues are silently suppressed by default. Use the `-ShowDebugInfo` parameter of `Register-ScriptFeedbackProvider` to get useful information for troubleshooting feedback providers. 8 | 9 | ## Usage 10 | A `[FeedbackContext]` is provided as an argument and you must return a single `[FeedbackItem]` object. 11 | 12 | You can access the feedback context either via `$args[0]` or as `param($context)` 13 | 14 | You can return a `[FeedbackItem]` result multiple ways: 15 | 16 | 1. Return a FeedbackItem object. This is the safest method. `[FeedbackItem]::new('header',@('action1','action2'))` 17 | 1. Return a single string, that will fill in for the header. 18 | 1. Return multiple strings, the first will be the header and the others will be the defined actions 19 | 1. Return a hashtable with the same properties as the FeedbackItem class. 20 | 21 | ## Examples 22 | 23 | ### Echo the last command 24 | 25 | ```powershell 26 | Register-ScriptFeedbackProvider -Name EchoCommand -Trigger All -ScriptBlock { 27 | param($context) 28 | [FeedbackItem]::new("Command was", $context.CommandLine) 29 | } 30 | ``` 31 | 32 | ![Alt text](images/README/image.png) 33 | 34 | ### Report on a recommended action 35 | 36 | ```powershell 37 | Register-ScriptFeedbackProvider -Name 'Error Recommended Action' { 38 | param($context) 39 | if ($context.LastError.ErrorDetails.RecommendedAction) { 40 | [FeedbackItem]::new( 41 | 'The last error has a recommended action:', 42 | $context.LastError.ErrorDetails.RecommendedAction 43 | ) 44 | } 45 | } 46 | ``` 47 | 48 | ![Alt text](images/README/image-1.png) 49 | 50 | ### Using simplified string syntax 51 | 52 | ```powershell 53 | Register-ScriptFeedbackProvider -Name 'Error Recommended Action' { 54 | param($context) 55 | if ($context.LastError.ErrorDetails.RecommendedAction) { 56 | 'The last error has a recommended action:' 57 | $context.LastError.ErrorDetails.RecommendedAction 58 | } 59 | } 60 | ``` 61 | ![Alt text](images/README/image-2.png) 62 | 63 | ## Authoring Intellisense 64 | 65 | To get intellisense for $context, add the namespace at the top of your file. 66 | 67 | ```powershell 68 | using namespace System.Management.Automation.Subsystem.Feedback 69 | { 70 | param([FeedbackContext]$context) 71 | $context. 72 | } 73 | ``` 74 | 75 | But do not include the namespace in your final command 76 | -------------------------------------------------------------------------------- /ScriptFeedbackProvider.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.002.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ScriptFeedbackProvider", "Source\ScriptFeedbackProvider.csproj", "{E2E56A9E-471D-4D54-AE89-19097E0D7B88}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {E2E56A9E-471D-4D54-AE89-19097E0D7B88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {E2E56A9E-471D-4D54-AE89-19097E0D7B88}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {E2E56A9E-471D-4D54-AE89-19097E0D7B88}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {E2E56A9E-471D-4D54-AE89-19097E0D7B88}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {EDBC183F-8416-4BCC-A90C-4D92BE50199D} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Source/Commands/GetScriptFeedbackProviderCommand.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | using static System.Management.Automation.Subsystem.SubsystemManager; 3 | using static System.Management.Automation.Subsystem.SubsystemKind; 4 | using static System.Management.Automation.Subsystem.SubsystemInfo; 5 | using static System.Management.Automation.VerbsCommon; 6 | 7 | namespace ScriptFeedbackProviderNS; 8 | 9 | [Cmdlet(Get, "ScriptFeedbackProvider")] 10 | public class GetScriptFeedbackProviderCommand : PSCmdlet 11 | { 12 | protected override void EndProcessing() 13 | { 14 | IEnumerable implementations = GetSubsystemInfo(FeedbackProvider) 15 | .Implementations 16 | .Where(i => i.ImplementationType == typeof(ScriptFeedbackProvider)); 17 | 18 | WriteObject(implementations, true); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Source/Commands/RegisterScriptFeedbackProviderCommand.cs: -------------------------------------------------------------------------------- 1 | using static System.Management.Automation.VerbsLifecycle; 2 | using System.Management.Automation; 3 | using System.Management.Automation.Subsystem.Feedback; 4 | 5 | namespace ScriptFeedbackProviderNS; 6 | 7 | [Cmdlet(Register, "ScriptFeedbackProvider")] 8 | public class RegisterScriptFeedbackProviderCommand : PSCmdlet 9 | { 10 | [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] 11 | /// 12 | /// A scriptblock that takes a FeedbackContext as a parameter and returns a FeedbackItem. 13 | /// 14 | public ScriptBlock? ScriptBlock; 15 | 16 | [Parameter(Position = 1)] 17 | public FeedbackTrigger? Trigger; 18 | 19 | [Parameter(Position = 2)] 20 | public string? Name; 21 | 22 | [Parameter(Position = 3)] 23 | public string? Description; 24 | 25 | [Parameter(Position = 4)] 26 | public Guid? Guid; 27 | 28 | [Parameter(Position = 5)] 29 | public SwitchParameter ShowDebugInfo; 30 | 31 | protected override void ProcessRecord() 32 | { 33 | var provider = new ScriptFeedbackProvider(ScriptBlock!, Name, Description, Guid, Trigger, ShowDebugInfo.IsPresent); 34 | provider.Register(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Source/Commands/UnregisterScriptFeedbackProviderCommand.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | using System.Management.Automation.Subsystem.Feedback; 3 | using static System.Management.Automation.Subsystem.SubsystemInfo; 4 | using static System.Management.Automation.Subsystem.SubsystemManager; 5 | using static System.Management.Automation.VerbsLifecycle; 6 | 7 | namespace ScriptFeedbackProviderNS; 8 | 9 | public interface SubsystemInfo 10 | { 11 | public Guid Id { get; } 12 | } 13 | 14 | [Cmdlet(Unregister, "ScriptFeedbackProvider")] 15 | public class UnRegisterScriptFeedbackProviderCommand : PSCmdlet 16 | { 17 | [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] 18 | public ImplementationInfo? Provider; 19 | 20 | protected override void ProcessRecord() 21 | { 22 | UnregisterSubsystem(Provider!.Id); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Source/FeedbackProvider.cs: -------------------------------------------------------------------------------- 1 |  2 | using static System.Management.Automation.Subsystem.SubsystemKind; 3 | using static System.Management.Automation.Subsystem.SubsystemManager; 4 | using System.Collections; 5 | using System.Management.Automation; 6 | using System.Management.Automation.Runspaces; 7 | using System.Management.Automation.Subsystem.Feedback; 8 | 9 | 10 | namespace ScriptFeedbackProviderNS; 11 | 12 | public class ScriptFeedbackProvider : IFeedbackProvider, IDisposable 13 | { 14 | public ScriptBlock ScriptBlock { get; init; } 15 | public string Name { get; init; } 16 | public string Description { get; init; } 17 | public Guid Id { get; init; } 18 | public bool ShowDebugInfo { get; init; } 19 | private PowerShell Ps { get; set; } 20 | 21 | public ScriptFeedbackProvider 22 | ( 23 | ScriptBlock scriptBlock, 24 | string? name, 25 | string? description, 26 | Guid? id, 27 | FeedbackTrigger? trigger, 28 | bool? showDebugInfo 29 | ) 30 | { 31 | ScriptBlock = scriptBlock; 32 | Name = name ?? "Script Based Feedback"; 33 | Description = description ?? "A feedback provider that runs a scriptblock"; 34 | Id = id ?? Guid.NewGuid(); 35 | Trigger = trigger ?? FeedbackTrigger.Error; 36 | ShowDebugInfo = showDebugInfo ?? false; 37 | Ps = PowerShell.Create(); 38 | } 39 | 40 | #region IFeedbackProvider 41 | public FeedbackTrigger Trigger { get; } 42 | public FeedbackItem? GetFeedback(FeedbackContext context, CancellationToken token) 43 | { 44 | PSDataCollection? results; 45 | 46 | try 47 | { 48 | // This should be uncommon but if our runspace is stuck due to an uncancelable script we need to swap it out for a fresh one and dispose the old one in the background. 49 | 50 | if (Ps.Runspace.RunspaceAvailability != RunspaceAvailability.Available) 51 | { 52 | if (ShowDebugInfo) 53 | Console.Error.WriteLine($"Script Feedback Provider {Name} ERROR: Runspace was still busy when we tried to resolve the next GetFeedback Request. This usually means your script is not cancelling correctly or fast enough."); 54 | 55 | var stuckPs = Ps; 56 | Ps = PowerShell.Create(); 57 | Ps.Runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); 58 | Ps.Runspace.Open(); 59 | 60 | _ = stuckPs.StopAsync(null, null); 61 | } 62 | 63 | var resultTask = Ps 64 | // Allows [FeedbackItem] to be used easily 65 | .AddScript("using namespace System.Management.Automation.Subsystem.Feedback") 66 | .AddScript(ScriptBlock.ToString()) 67 | .AddArgument(context) 68 | .InvokeAsync(); 69 | 70 | // The feedback provider silently times out at 300ms so we want to make this explicit. 71 | if (!resultTask.Wait(250)) 72 | { 73 | if (ShowDebugInfo) 74 | Console.Error.WriteLine($"Script Feedback Provider {Name} ERROR: Script took longer than 250ms to execute. Feedback providers must complete in 300ms or less."); 75 | 76 | // Cancel the script 77 | _ = Ps.StopAsync(null, null); 78 | return null; 79 | } 80 | 81 | results = resultTask.GetAwaiter().GetResult(); 82 | } 83 | catch (Exception err) 84 | { 85 | if (ShowDebugInfo) 86 | Console.Error.WriteLine($"Script Feedback Provider {Name} ERROR: {err}"); 87 | 88 | return null; 89 | } 90 | finally 91 | { 92 | Ps.Commands.Clear(); 93 | } 94 | 95 | return HandleFeedbackResult(results); 96 | } 97 | #endregion IFeedbackProvider 98 | 99 | public void Register() 100 | { 101 | RegisterSubsystem(FeedbackProvider, this); 102 | // Initialize and warm up the runspace to speed up later invocation 103 | Ps.Runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); 104 | Ps.Runspace.Open(); 105 | } 106 | 107 | public void Dispose() 108 | { 109 | UnregisterSubsystem(Id); 110 | } 111 | 112 | private FeedbackItem? HandleFeedbackResult(PSDataCollection result) 113 | { 114 | if (result.Count < 1) 115 | { 116 | if (ShowDebugInfo) 117 | Console.Error.WriteLine($"Script Feedback Provider {Name} INFO: The script produced no output. This is normal if your feedback provider was not applicable/relevant"); 118 | 119 | return null; 120 | } 121 | 122 | // If a feedbackItem was returned, return it 123 | var feedbackItemResult = result 124 | .Select(x => x.BaseObject) 125 | .OfType() 126 | .ToList(); 127 | 128 | if (feedbackItemResult.Count > 0) 129 | { 130 | if (ShowDebugInfo && feedbackItemResult.Count > 1) 131 | Console.Error.WriteLine($"Script Feedback Provider {Name} WARN: Multiple feedback items were received, only the first will be used. This usually means your feedback provider was written incorrectly."); 132 | 133 | return feedbackItemResult[0]; 134 | } 135 | 136 | 137 | 138 | List hashTableResult = result 139 | .Select(x => x.BaseObject) 140 | .OfType() 141 | .ToList(); 142 | 143 | if (hashTableResult.Count > 0) 144 | { 145 | if (ShowDebugInfo && hashTableResult.Count > 0) 146 | Console.Error.WriteLine($"Script Feedback Provider {Name} WARN: Multiple hashtables/dictionaries were received, only the first will be used. This usually means your feedback provider was written incorrectly, it shoud only return one hashtable/dictionary if this is the method you are using."); 147 | 148 | var dict = hashTableResult[0]; 149 | 150 | if (!(dict.Contains("header") && dict["header"] is string header)) 151 | { 152 | Console.Error.WriteLine($"Script Feedback Provider {Name} ERROR: Your script returned a hashtable/dictionary but it did not contain a 'header' key with a string value. This usually means your feedback provider was written incorrectly, your supplied hashtable/dictionary should contain a 'header' key with a string value."); 153 | return null; 154 | } 155 | 156 | if (!dict.Contains("actions")) 157 | return new FeedbackItem(header, null); 158 | 159 | if (dict["actions"] is string action) 160 | { 161 | return new FeedbackItem(header, [action]); 162 | } 163 | 164 | string[]? actionsArray = dict["actions"] as string[]; 165 | 166 | if (actionsArray == null) 167 | { 168 | Console.Error.WriteLine($"Script Feedback Provider {Name} ERROR: Your script returned a hashtable/dictionary that had an 'actions' key with something other a string array value. This usually means your feedback provider was written incorrectly, your supplied hashtable/dictionary should contain an 'actions' key with a string array value."); 169 | return null; 170 | } 171 | 172 | return new FeedbackItem(header, actionsArray.ToList()); 173 | } 174 | 175 | // If string(s) was returned, convert it to a feedback item 176 | var stringResult = result 177 | .Select(x => x.BaseObject) 178 | .OfType() 179 | .ToList(); 180 | 181 | if (stringResult.Count == 1) 182 | { 183 | return new FeedbackItem(stringResult[0], null); 184 | } 185 | if (stringResult.Count > 1) 186 | { 187 | string header = stringResult[0]; 188 | stringResult.RemoveAt(0); 189 | return new FeedbackItem(header, stringResult); 190 | } 191 | 192 | Console.Error.WriteLine($"Script Feedback Provider {Name} ERROR: An unsupported object was output by your script. Only FeedbackProvider or string are supported."); 193 | return null; 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /Source/ScriptFeedbackProvider.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | portable 11 | en 12 | false 13 | true 14 | ../Release 15 | true 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Source/ScriptFeedbackProvider.psd1: -------------------------------------------------------------------------------- 1 | # 2 | # Module manifest for module 'MgAqDetect' 3 | # 4 | # Generated by: Justin Grote @JustinWGrote 5 | # 6 | # Generated on: 10/30/2023 7 | # 8 | 9 | @{ 10 | 11 | # Script module or binary module file associated with this manifest. 12 | RootModule = './ScriptFeedbackProvider.dll' 13 | 14 | # Version number of this module. 15 | ModuleVersion = '0.0.0' 16 | 17 | # Supported PSEditions 18 | # CompatiblePSEditions = @() 19 | 20 | # ID used to uniquely identify this module 21 | GUID = '79c953dc-e392-4244-8a37-cd050be5207c' 22 | 23 | # Author of this module 24 | Author = 'Justin Grote @JustinWGrote github.com/JustinGrote' 25 | 26 | # Company or vendor of this module 27 | CompanyName = 'Unspecified' 28 | 29 | # Copyright statement for this module 30 | Copyright = '©2023 Justin Grote @JustinWGrote' 31 | 32 | # Description of the functionality provided by this module 33 | Description = 'Allows registration of Feedback Providers written as PowerShell scripts' 34 | 35 | # Minimum version of the PowerShell engine required by this module 36 | PowerShellVersion = '7.4' 37 | 38 | # Name of the PowerShell host required by this module 39 | # PowerShellHostName = '' 40 | 41 | # Minimum version of the PowerShell host required by this module 42 | # PowerShellHostVersion = '' 43 | 44 | # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. 45 | # DotNetFrameworkVersion = '' 46 | 47 | # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. 48 | # ClrVersion = '' 49 | 50 | # Processor architecture (None, X86, Amd64) required by this module 51 | # ProcessorArchitecture = '' 52 | 53 | # Modules that must be imported into the global environment prior to importing this module 54 | # RequiredModules = @() 55 | 56 | # Assemblies that must be loaded prior to importing this module 57 | # RequiredAssemblies = @() 58 | 59 | # Script files (.ps1) that are run in the caller's environment prior to importing this module. 60 | # ScriptsToProcess = @() 61 | 62 | # Type files (.ps1xml) to be loaded when importing this module 63 | # TypesToProcess = @() 64 | 65 | # Format files (.ps1xml) to be loaded when importing this module 66 | # FormatsToProcess = @() 67 | 68 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess 69 | # NestedModules = @() 70 | 71 | # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. 72 | FunctionsToExport = '*' 73 | 74 | # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. 75 | CmdletsToExport = '*' 76 | 77 | # Variables to export from this module 78 | VariablesToExport = '*' 79 | 80 | # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. 81 | AliasesToExport = '*' 82 | 83 | # DSC resources to export from this module 84 | # DscResourcesToExport = @() 85 | 86 | # List of all modules packaged with this module 87 | # ModuleList = @() 88 | 89 | # List of all files packaged with this module 90 | # FileList = @() 91 | 92 | # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. 93 | PrivateData = @{ 94 | 95 | PSData = @{ 96 | 97 | # Tags applied to this module. These help with module discovery in online galleries. 98 | # Tags = @() 99 | 100 | # A URL to the license for this module. 101 | LicenseUri = 'https://github.com/JustinGrote/ScriptFeedbackProvider/blob/main/LICENSE' 102 | 103 | # A URL to the main website for this project. 104 | ProjectUri = 'https://github.com/JustinGrote/ScriptFeedbackProvider' 105 | 106 | # A URL to an icon representing this module. 107 | # IconUri = '' 108 | 109 | # ReleaseNotes of this module 110 | # ReleaseNotes = '' 111 | 112 | # Prerelease string of this module 113 | Prerelease = 'SOURCE' 114 | 115 | # Flag to indicate whether the module requires explicit user acceptance for install/update/save 116 | # RequireLicenseAcceptance = $false 117 | 118 | # External dependent modules of this module 119 | # ExternalModuleDependencies = @() 120 | 121 | } # End of PSData hashtable 122 | 123 | } # End of PrivateData hashtable 124 | 125 | # HelpInfo URI of this module 126 | # HelpInfoURI = '' 127 | 128 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. 129 | # DefaultCommandPrefix = '' 130 | 131 | } 132 | 133 | -------------------------------------------------------------------------------- /Source/packages.lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "dependencies": { 4 | "net8.0": { 5 | "System.Management.Automation": { 6 | "type": "Direct", 7 | "requested": "[7.4.0-rc.1, )", 8 | "resolved": "7.4.0-rc.1", 9 | "contentHash": "te+FiXU1nZRvrjVQ4Pgw+LZS9UvlW0YWEhVOeDV8LkHT7LRWpvW8O+uAJW+8SazngoAu3BPZCOBlfqvp6eU/9g==", 10 | "dependencies": { 11 | "Microsoft.ApplicationInsights": "2.21.0", 12 | "Microsoft.Management.Infrastructure": "3.0.0-preview.4", 13 | "Microsoft.PowerShell.CoreCLR.Eventing": "7.4.0-rc.1", 14 | "Microsoft.PowerShell.Native": "7.4.0-preview.2", 15 | "Microsoft.Security.Extensions": "1.2.0", 16 | "Microsoft.Win32.Registry.AccessControl": "8.0.0-rc.2.23479.6", 17 | "Newtonsoft.Json": "13.0.3", 18 | "System.Configuration.ConfigurationManager": "8.0.0-rc.2.23479.6", 19 | "System.Diagnostics.DiagnosticSource": "8.0.0-rc.2.23479.6", 20 | "System.DirectoryServices": "8.0.0-rc.2.23479.6", 21 | "System.Management": "8.0.0-rc.2.23479.6", 22 | "System.Security.AccessControl": "6.0.2-mauipre.1.22102.15", 23 | "System.Security.Cryptography.Pkcs": "8.0.0-rc.2.23479.6", 24 | "System.Security.Permissions": "8.0.0-rc.2.23479.6", 25 | "System.Text.Encoding.CodePages": "8.0.0-rc.2.23479.6" 26 | } 27 | }, 28 | "Microsoft.ApplicationInsights": { 29 | "type": "Transitive", 30 | "resolved": "2.21.0", 31 | "contentHash": "btZEDWAFNo9CoYliMCriSMTX3ruRGZTtYw4mo2XyyfLlowFicYVM2Xszi5evDG95QRYV7MbbH3D2RqVwfZlJHw==", 32 | "dependencies": { 33 | "System.Diagnostics.DiagnosticSource": "5.0.0" 34 | } 35 | }, 36 | "Microsoft.Management.Infrastructure": { 37 | "type": "Transitive", 38 | "resolved": "3.0.0-preview.4", 39 | "contentHash": "kCKOZLxT8satC4vCmXD2rA1tGGSkluB4s/iRQMtnbcLvqLzQyuT68b3+WEz6QvKUEGowjldRtPV/C/+aG0074g==", 40 | "dependencies": { 41 | "Microsoft.Management.Infrastructure.Runtime.Unix": "3.0.0-preview.4", 42 | "Microsoft.Management.Infrastructure.Runtime.Win": "3.0.0-preview.4" 43 | } 44 | }, 45 | "Microsoft.Management.Infrastructure.Runtime.Unix": { 46 | "type": "Transitive", 47 | "resolved": "3.0.0-preview.4", 48 | "contentHash": "8/DtnXtaykwi+s4bW/mAxVP9VYkI6dDMsLX544YT/s/4E3TIrhw+1dcs8UxZ8Ryl0QSRMR+LPyinxP/7KdFOwQ==" 49 | }, 50 | "Microsoft.Management.Infrastructure.Runtime.Win": { 51 | "type": "Transitive", 52 | "resolved": "3.0.0-preview.4", 53 | "contentHash": "rVceAcbK2OQJNtVNnRPDtEiKuT571hNGpJoEuGgmB3eVGxvZQn5L0Otntbl8R6RMZaDj/Z/bi1c4vnF+tKI9MQ==" 54 | }, 55 | "Microsoft.PowerShell.CoreCLR.Eventing": { 56 | "type": "Transitive", 57 | "resolved": "7.4.0-rc.1", 58 | "contentHash": "qfhV3xxrdJx4A3Uiwat4IEBJigaJUFXugXwb8JbgGHofyPxDCdB10ICuT6cRhP8VrtxCLzyR+peAi6Wj2zE3Rw==", 59 | "dependencies": { 60 | "System.Diagnostics.EventLog": "8.0.0-rc.2.23479.6" 61 | } 62 | }, 63 | "Microsoft.PowerShell.Native": { 64 | "type": "Transitive", 65 | "resolved": "7.4.0-preview.2", 66 | "contentHash": "Nb0JZWsK2rhulC9wIalsQCUNokcS8RE7j/RU8V4SJeuZ4jVMQAt/wLDedpw6/OFQPKJp5ZBV9thH8g7q7Ofpnw==" 67 | }, 68 | "Microsoft.Security.Extensions": { 69 | "type": "Transitive", 70 | "resolved": "1.2.0", 71 | "contentHash": "GjHZBE5PHKrxPRyGujWQKwbKNjPQYds6HcAWKeV49X3KPgBfF2B1vV5uJey5UluyGQlvAO/DezL7WzEx9HlPQA==" 72 | }, 73 | "Microsoft.Win32.Registry.AccessControl": { 74 | "type": "Transitive", 75 | "resolved": "8.0.0-rc.2.23479.6", 76 | "contentHash": "pcjiGDsgz/8MaTJwsLj0UKIx0F6fYXd1GfAR7QFkmprDRU9JVW3WWMegs9ewGNxlG6TgBJxCVO2WY3645U+ezw==" 77 | }, 78 | "Newtonsoft.Json": { 79 | "type": "Transitive", 80 | "resolved": "13.0.3", 81 | "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" 82 | }, 83 | "System.CodeDom": { 84 | "type": "Transitive", 85 | "resolved": "8.0.0-rc.2.23479.6", 86 | "contentHash": "aeGoz8+QUeJVevfqHPe5F7EvNRQmbfOltyrsjpKfJmvD4ltJ2B4nXV5yX9iIYsnyvCZ2iwe5Kwc1YN5SuD7RUA==" 87 | }, 88 | "System.Configuration.ConfigurationManager": { 89 | "type": "Transitive", 90 | "resolved": "8.0.0-rc.2.23479.6", 91 | "contentHash": "xrca21E/7vnHe45MvfcS4J2sj0vzTUsnQxO2dhe2Ex49RZ5qfeZF9bTDp7es+zTp6YZA2xUJLbrFySbrpHqW4Q==", 92 | "dependencies": { 93 | "System.Diagnostics.EventLog": "8.0.0-rc.2.23479.6", 94 | "System.Security.Cryptography.ProtectedData": "8.0.0-rc.2.23479.6" 95 | } 96 | }, 97 | "System.Diagnostics.DiagnosticSource": { 98 | "type": "Transitive", 99 | "resolved": "8.0.0-rc.2.23479.6", 100 | "contentHash": "D1Fi5wRyRVwriEdlSniYlo2kW8SCGaSCM/alsY8R7eXcW+xCPRB7gohE45X00EiNkhdUrJ3yNfltV8lLK0HoWQ==" 101 | }, 102 | "System.Diagnostics.EventLog": { 103 | "type": "Transitive", 104 | "resolved": "8.0.0-rc.2.23479.6", 105 | "contentHash": "HMyVSVGuhpzOV1y8j/+y2HZAAo7E1m8WhSZCDsgDG6GDzrUL3voCURbrBlAeLNParK8QNO5Ht06ccWuXOMLYIA==" 106 | }, 107 | "System.DirectoryServices": { 108 | "type": "Transitive", 109 | "resolved": "8.0.0-rc.2.23479.6", 110 | "contentHash": "qQ5oXDl7GuU5ggAa7uYURGlUcPvItHRTZZ+9zhtbTUOIUjaNF2uroNOOVNRoUe/rAQQ11ynBGss9VRfRxmVaNQ==" 111 | }, 112 | "System.Formats.Asn1": { 113 | "type": "Transitive", 114 | "resolved": "8.0.0-rc.2.23479.6", 115 | "contentHash": "A1p1/ATQf4KawXEDccim1SUrZBlEg/fEzQ9U8WnmY63xe3PIIxNRDa0sz+D7SOiMJvA/7Z3TzuTdpg4qQqJj2w==" 116 | }, 117 | "System.Management": { 118 | "type": "Transitive", 119 | "resolved": "8.0.0-rc.2.23479.6", 120 | "contentHash": "JONr3YTgi9PwZGb7qdJo2tqx0yauj2EJhmc3vCHuhijM9H5DowRlaw7Vuuml0RAgow4BghxcTwjc/wGC8ywIqg==", 121 | "dependencies": { 122 | "System.CodeDom": "8.0.0-rc.2.23479.6" 123 | } 124 | }, 125 | "System.Security.AccessControl": { 126 | "type": "Transitive", 127 | "resolved": "6.0.2-mauipre.1.22102.15", 128 | "contentHash": "ny0SrGGm/O1Q889Zzx1tLP8X0UjkOHjDPN0omy3onMwU1qPrPq90kWvMY8gmh6eHtRkRAGzlJlEer64ii7GMrg==" 129 | }, 130 | "System.Security.Cryptography.Pkcs": { 131 | "type": "Transitive", 132 | "resolved": "8.0.0-rc.2.23479.6", 133 | "contentHash": "2es7eO33NRs8q639HHhwF45WV1L/gPuR2c43gTRFD0uwIM/iFQr7VK13PQoYPPxh/8AczRvEPXGwjwXJ+KQ7yw==", 134 | "dependencies": { 135 | "System.Formats.Asn1": "8.0.0-rc.2.23479.6" 136 | } 137 | }, 138 | "System.Security.Cryptography.ProtectedData": { 139 | "type": "Transitive", 140 | "resolved": "8.0.0-rc.2.23479.6", 141 | "contentHash": "PhyL+Qv4bYnWlh/AxIdye89bBxwsyJdGXEFugJgICTQaVbq39p9q1Bal5a+HF14goo2vICFxwEEyb0Gr0jln/w==" 142 | }, 143 | "System.Security.Permissions": { 144 | "type": "Transitive", 145 | "resolved": "8.0.0-rc.2.23479.6", 146 | "contentHash": "EcRrJY11Z16plv8VGkdoMf5lxcxoglLgW2p+OHTwmsGFETvhy5d+v/YQhQaGhHlwrdgkO+/UnSklp81ww446Zg==", 147 | "dependencies": { 148 | "System.Windows.Extensions": "8.0.0-rc.2.23479.6" 149 | } 150 | }, 151 | "System.Text.Encoding.CodePages": { 152 | "type": "Transitive", 153 | "resolved": "8.0.0-rc.2.23479.6", 154 | "contentHash": "ujGSxbRGaEnQOUd/7WJy5MwW/fsrl7dt+WXqDYjRoLrqt0xY1yZp5SZ9wUNtLIpEf2UPLXmaperWdjzq9gX7ew==" 155 | }, 156 | "System.Windows.Extensions": { 157 | "type": "Transitive", 158 | "resolved": "8.0.0-rc.2.23479.6", 159 | "contentHash": "HA8E+RWlb7kKvj5n2JzIj0jIylCgjJ5arDqylmI94wO4EMsoinVGaYklTSxYE4NuVcnKfxbun3k1UVdK7Kolsw==" 160 | } 161 | } 162 | } 163 | } -------------------------------------------------------------------------------- /images/README/image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JustinGrote/ScriptFeedbackProvider/e540847ca580bc218f570758e5fd04b033416c13/images/README/image-1.png -------------------------------------------------------------------------------- /images/README/image-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JustinGrote/ScriptFeedbackProvider/e540847ca580bc218f570758e5fd04b033416c13/images/README/image-2.png -------------------------------------------------------------------------------- /images/README/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JustinGrote/ScriptFeedbackProvider/e540847ca580bc218f570758e5fd04b033416c13/images/README/image.png --------------------------------------------------------------------------------