"Type expected" Powershell 添加类型代码块中的错误。 DllImport,Windows 已知文件夹

"Type expected" error in Powershell Add-Type code block . DllImport, Windows Known Folders

我正在尝试。ps1

Add-Type -TypeDefinition @'
using System;       // IntPtr
using System.Runtime;       // guid Type
using System.Runtime.InteropServices;       // DllImport

public class Win32 {
    public static class KnownFolderId {
        public static readonly Guid Desktop = new(0xB4BFCC3A, 0xDB2C, 0x424C, 0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41);
    }

    [DllImport("shell32.dll")] static extern int SHGetKnownFolderPath(
        [MarshalAs(UnmanagedType.LPStruct)] Guid rfid,
        uint dwFlags,
        IntPtr hToken,
        out IntPtr ppszPath
    );
                
    public static string? GetKnownFolderPath() {
        IntPtr ppszPath = default;
        try {
            int hr = SHGetKnownFolderPath(Win32.KnownFolderId.Desktop, 0, IntPtr.Zero, out ppszPath);
            Marshal.ThrowExceptionForHR(hr); // alternatively, check success with hr >= 0
            return Marshal.PtrToStringUni(ppszPath);
        }
        finally {
            Marshal.FreeCoTaskMem(ppszPath);
        }
    }

}
'@
[Win32]::GetKnownFolderPath() | write-host

read-host 'end'

当然还有这个

Type expected
<<..>>\h1c5k4r2.0.cs(5) : public static class KnownFolderId {
<<..>>\h1c5k4r2.0.cs(6) : >>>     public static readonly Guid Desktop = new(0xB4BFCC3A,<<..>>

1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345[17890]

您正在使用 Add-TypeWindows 中使用的编译器 PowerShell 不支持的 C# 语言功能,特别是:

  • new(...),没有类型名称的构造函数调用 - 替换为 new Guid(...)

  • default 表示类型的默认值 - 替换为 IntPtr.Zero.

  • string?,一个可为 null 的注释 - 删除 ?

因此,使用以下内容:

Add-Type -TypeDefinition @'
using System;       // IntPtr
using System.Runtime;       // guid Type
using System.Runtime.InteropServices;       // DllImport

public class Win32 {
    public static class KnownFolderId {
        public static readonly Guid Desktop = new Guid(0xB4BFCC3A, 0xDB2C, 0x424C, 0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41);
    }

    [DllImport("shell32.dll")] static extern int SHGetKnownFolderPath(
        [MarshalAs(UnmanagedType.LPStruct)] Guid rfid,
        uint dwFlags,
        IntPtr hToken,
        out IntPtr ppszPath
    );
                
    public static string GetKnownFolderPath() {
        IntPtr ppszPath = IntPtr.Zero;
        try {
            int hr = SHGetKnownFolderPath(Win32.KnownFolderId.Desktop, 0, IntPtr.Zero, out ppszPath);
            Marshal.ThrowExceptionForHR(hr); // alternatively, check success with hr >= 0
            return Marshal.PtrToStringUni(ppszPath);
        }
        finally {
            Marshal.FreeCoTaskMem(ppszPath);
        }
    }

}
'@

[Win32]::GetKnownFolderPath()

注:

  • PowerShell (Core) 7+ 中,Add-Type 支持这些语言功能。

  • 在那里,唯一需要做的更改是在源代码的第一行之前放置 #nullable enable,以便启用可为空的注释。