如何检查 powershell 脚本是否是从托管 API 签名的?

Jam*_*rry 3 powershell

我想使用 .net Powershell SDK 执行 powershell。我这个工作正常。在执行之前,我想检查脚本是否已由我的代码签名证书签名 - 这很容易在 powershell 本身内使用 Get-AuthenticodeSignature 完成,但我想在选择执行此脚本之前在代码中执行此操作。

解决方案:

        Runspace runSpace = RunspaceFactory.CreateRunspace();
        runSpace.Open();

        Pipeline shell = runSpace.CreatePipeline();
        shell.Commands.AddScript(String.Format("Get-AuthenticodeSignature '{0}'", Filename));

        Signature sig = (shell.Invoke()[0]).BaseObject as Signature;
        bool isValid = sig.Status == SignatureStatus.Valid;
Run Code Online (Sandbox Code Playgroud)

x0n*_*x0n 5

我能想到的最简单的方法是仍然使用 powershell,但是在托管代码中:

using System.Management.Automation;

void Foo(string path) {
   PowerShell shell = PowerShell.Create();
   shell.AddScript(String.Format("Get-AuthenticodeSignature {0}", path));

   Signature sig = shell.Invoke()[0] as Signature; // returns collection
   bool isValid = sig.Valid;
}
Run Code Online (Sandbox Code Playgroud)

(根据记忆,所以语法上可能不完全正确)