I'm writing a C# cmdlet to install and uninstall various products in a standardized way via a script. This includes a log file (via NLog) that is created and filled at runtime. PSScriptRoot and ScriptName are listed in the header of the log file and is also needed in other steps.
I thought I could use this.MyInvocation for this, but unfortunately the object is always empty.
Here's an example:
namespace MyCmdlet
{
[Cmdlet(VerbsData.Update, "Environment")]
[OutputType(typeof(UpdateEnvironment))]
public partial class UpdateEnvironment : PSCmdlet
{
# Some parameters
protected override void ProcessRecord()
{
base.ProcessRecord();
string currentTime = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss");
string toReturn = string.Empty;
InvocationInfo iInfo = this.MyInvocation;
// For testing
var a = PSCmdlet.MyInvocation.PSScriptRoot;
// Should be filled
GlobalProps.psScriptRoot = this.MyInvocation.PSScriptRoot;
GlobalProps.psScriptName = this.MyInvocation.ScriptName;
...
...
}
}
}
How do I test? -
In Visual Studio → Project → Setting → Debugging, I start an external program ("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe") and in the start options I add these arguments: -noexit -command "&{ import-module .\MyCmdlets.dll -verbose}"
After starting, I fill in some variables for testing in the current opened PowerShell console
Finally I call my cmdlet.
Other tests...
...has the same effect. MyInvocation.PSSCriptRoot, ScriptName, ... are empty. How can I use this?
OK! I have found a solution!
InvocationInfo is processed correctly. But only 1x. Now I save the information in a static variable and then only work with it.