PowerShell Module mit Visual Studio Code

Um in VS Code das IntelliSense für alle seine Module nutzen zu können, ist es notwendig auch die entsprechenden PowerShell Module mit Visual Studio Code beim Start zu laden. Da leider auf den ersten Blick nicht ganz klar ist wie das funktioniert, habe ich die nötigen Schritte in diesem Artikel zusammengefasst.

Beispiel für IntelliSense mit VMware PowerCLI:

PowerShell Module mit Visual Studio Code - intellisense

Um die gewünschten PowerShell Module mit Visual Studio Code zu laden kann VS Code die PowerShell User oder System Profile nutzen (Mehr Details zu PowerShell Profilen).

Um das Laden der PowerShell Profile in VS Code zu aktiveren muss folgende Option gesetzt sein:

"powershell.enableProfileLoading": true

PowerShell Module mit Visual Studio Code – Das Profil

Das PowerShell User Profil für VS Code muss hier angelegt werden:

„C:\Users\<YouUser>\Documents\WindowsPowerShell\Microsoft.VSCode_profile.ps1“

Für VS Code und ISE verwende ich ein schlankes Profil:

$moduleList = @(
	"Pester"
	"PSScriptAnalyzer"
    "VMware.VimAutomation.Core",
    "VMware.VimAutomation.Vds",
    "VMware.VimAutomation.Cloud",
    "VMware.VimAutomation.PCloud",
    "VMware.VimAutomation.Cis.Core",
    "VMware.VimAutomation.Storage",
    "VMware.VimAutomation.HorizonView",
    "VMware.VimAutomation.HA",
    "VMware.VimAutomation.vROps",
    "VMware.VumAutomation",
    "VMware.DeployAutomation",
    "VMware.ImageBuilder",
    "VMware.VimAutomation.License"
    )

function LoadModules(){
   
   $loaded = Get-Module -Name $moduleList -ErrorAction Ignore | % {$_.Name}
   $registered = Get-Module -Name $moduleList -ListAvailable -ErrorAction Ignore | % {$_.Name}
   $notLoaded = $registered | ? {$loaded -notcontains $_}
   
   foreach ($module in $registered) {
      if ($loaded -notcontains $module) {
         
		 Import-Module $module
		 
      }
   }
}

LoadModules

Mein vollständiges PowerShell Profil ist etwas aufgehübscht:

$moduleList = @(
	"Pester"
	"PSScriptAnalyzer"
    "VMware.VimAutomation.Core",
    "VMware.VimAutomation.Vds",
    "VMware.VimAutomation.Cloud",
    "VMware.VimAutomation.PCloud",
    "VMware.VimAutomation.Cis.Core",
    "VMware.VimAutomation.Storage",
    "VMware.VimAutomation.HorizonView",
    "VMware.VimAutomation.HA",
    "VMware.VimAutomation.vROps",
    "VMware.VumAutomation",
    "VMware.DeployAutomation",
    "VMware.ImageBuilder",
    "VMware.VimAutomation.License"
    )

$productName = "My PowerShell"
$productShortName = "My PS"

$loadingActivity = "Loading $productName"
$script:completedActivities = 0
$script:percentComplete = 0
$script:currentActivity = ""
$script:totalActivities = `
   $moduleList.Count + 1

function ReportStartOfActivity($activity) {
   $script:currentActivity = $activity
   Write-Progress -Activity $loadingActivity -CurrentOperation $script:currentActivity -PercentComplete $script:percentComplete
}
function ReportFinishedActivity() {
   $script:completedActivities++
   $script:percentComplete = (100.0 / $totalActivities) * $script:completedActivities
   $script:percentComplete = [Math]::Min(99, $percentComplete)
   
   Write-Progress -Activity $loadingActivity -CurrentOperation $script:currentActivity -PercentComplete $script:percentComplete
}

function LoadModules(){
   ReportStartOfActivity "Searching for $productShortName module components..."
   
   $loaded = Get-Module -Name $moduleList -ErrorAction Ignore | % {$_.Name}
   $registered = Get-Module -Name $moduleList -ListAvailable -ErrorAction Ignore | % {$_.Name}
   $notLoaded = $registered | ? {$loaded -notcontains $_}
   
   ReportFinishedActivity
   
   foreach ($module in $registered) {
      if ($loaded -notcontains $module) {
		 ReportStartOfActivity "Loading module $module"
         
		 Import-Module $module
		 
		 ReportFinishedActivity
      }
   }
}

LoadModules

cd /

Durch mich modifizierte Quelle: VMware POwerCLI Initialize-PowerCLIEnvironment.ps1

PowerShell Language Support for Visual Studio Code

Ein absolutes must have für alle Visual Studio Code PowerShell Skripter!

Features:

  • Syntax highlighting
  • Code snippets
  • IntelliSense for cmdlets and more
  • Rule-based analysis provided by PowerShell Script Analyzer
  • Go to Definition of cmdlets and variables
  • Find References of cmdlets and variables
  • Document and workspace symbol discovery
  • Run selected selection of PowerShell code using F8
  • Launch online help for the symbol under the cursor using Ctrl+F1
  • Local script debugging and basic interactive console support!

Mehr Details sind in der vscode-powershell GitHub README zu finden.

PowerShell Module mit Visual Studio Code - extension powershell

PowerShell Module mit Visual Studio Code – Die Einstellungen

In VS Code gibt es verschiedenste Stellen für die Einstellung (Mehr Details zu den Einstellungen).

Grundlegend gibt es zwei Typen:

  • User Diese Einstellungen gelten global für all VS Code Instanzen die durch den Benutzer gestartet werden
  • Workspace Diese Einstellungen werden innerhalb des aktuellen Arbeitsbereich im Ordner „.vscode“ gespeichert und gelten nur wenn dieser Arbeitsbereich geladen ist.

Öffnen der Einstellungen:

PowerShell Module mit Visual Studio Code - settings

Default PowerShell Settings

In den aktuellen VS Code Versionen und der PowerShell Extension ist das Laden der PowerShell Profile bereits aktiviert.

PowerShell Module mit Visual Studio Code - default settings

// PowerShell Configuration

    // If true, causes the 32-bit language service to be used on 64-bit Windows.  On 32-bit Windows this setting has no effect.  This setting does not affect the debugger which has its own architecture configuration.
    "powershell.useX86Host": false,

    // If true, causes user and system wide profiles (profile.ps1 and Microsoft.VSCode_profile.ps1) to be loaded into the PowerShell session.  This affects IntelliSense and interactive script execution.  The debugger is not affected by this setting.
    "powershell.enableProfileLoading": true,

    // Enables real-time script analysis using PowerShell Script Analyzer.
    "powershell.scriptAnalysis.enable": true,

    // Specifies the path to a PowerShell Script Analyzer settings file. Use either an absolute path (to override the default settings for all projects) or use a path relative to your workspace.
    "powershell.scriptAnalysis.settingsPath": "",

    // Specifies the full path to a PowerShell executable.  Used to change the installation of PowerShell used for language and debugging services.
    "powershell.developer.powerShellExePath": "",

    // Specifies the path to the folder containing modules that are bundled with the PowerShell extension (i.e. PowerShell Editor Services, PowerShell Script Analyzer, Plaster)
    "powershell.developer.bundledModulesPath": "../modules/",

    // Sets the logging verbosity level for the PowerShell Editor Services host executable.  Possible values are 'Verbose', 'Normal', 'Warning', and 'Error'
    "powershell.developer.editorServicesLogLevel": "Normal",

    // Launches the language service with the /waitForDebugger flag to force it to wait for a .NET debugger to attach before proceeding.
    "powershell.developer.editorServicesWaitForDebugger": false

}

User Settings

Eigentlich ist diese zusätzliche Einstellung mit den Standardeinstellungen redundant. Ich möchte aber dennoch die Syntax aufzeigen.

PowerShell Module mit Visual Studio Code - user settings

// Place your settings in this file to overwrite the default settings

{
    "powershell.enableProfileLoading": true
}

Leave a Reply