【问题标题】:C# Binary CmdLet this.MyInvocation.PSScriptRoot is emptyC# 二进制 CmdLet this.MyInvocation.PSScriptRoot 为空
【发布时间】:2020-06-04 17:35:56
【问题描述】:

我正在编写一个 C# cmdlet,以通过脚本以标准化方式安装和卸载各种产品。这包括在运行时创建和填充的日志文件(通过 NLog)。 PSScriptRoot 和 ScriptName 列在日志文件的标题中,在其他步骤中也需要。

我以为我可以为此使用 this.MyInvocation,但不幸的是,该对象始终为空。

这是一个例子:

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;
            ...
            ...
        }
    }
}

我如何测试? -

  • 在 Visual Studio → ProjectSettingDebugging 中,我启动了一个外部程序(“C:\Windows\System32\WindowsPowerShell\ v1.0\powershell.exe") 并在启动选项中添加这些参数: -noexit -command "&{ import-module .\MyCmdlets.dll -verbose}"

  • 启动后,我在当前打开的PowerShell控制台中填写一些变量进行测试

  • 最后我调用了我的 cmdlet。

其他测试...

...具有相同的效果。 MyInvocation.PSSCriptRoot, ScriptName, ... 为空。我该如何使用它?

【问题讨论】:

    标签: c# powershell-cmdlet


    【解决方案1】:

    好的!我找到了解决办法!

    InvocationInfo 被正确处理。但只有 1 倍。现在我将信息保存在一个静态变量中,然后只使用它。

    【讨论】:

    • “但只有 1x” 是什么意思?你能详细说明吗?请通过editing (changing) your answer 回复,而不是在 cmets 中(without "Edit:"、"Update:" 或类似的 - 答案应该看起来像是今天写的)。
    猜你喜欢
    • 2023-03-24
    • 2017-10-16
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2015-11-28
    • 2019-03-18
    • 1970-01-01
    • 2015-09-19
    相关资源
    最近更新 更多