使用HereStrings在Windows Powershell中添加枚举类型



我使用5.1版的Windows Powershell ISE从目录中读取文件,然后希望将这些文件名添加到Enum中以供以后使用。我找到了一种方法,通过HereString传递C#代码。

#where the files would be read
Param([Parameter(Mandatory=$True, Position=0)][ValidateNotNullOrEmpty()][String]$path)
#search for files in the path directory
$files = Get-ChildItem $path -Name
$HereString = @"
public enum Files
{
$(
foreach($file in $files){$file}
{
"$file,"
}
)
}
"@
Add-Type -TypeDefinition $HereString

如果我不尝试传入文件名(通过声明一个简单的Enum(,那么代码运行良好。但此代码会出现以下错误:

Add-Type : c:UsersHPCAppDataLocalTemp1n43jzgm.0.cs(3) : } expected
c:UsersHPCAppDataLocalTemp1n43jzgm.0.cs(2) : {
c:UsersHPCAppDataLocalTemp1n43jzgm.0.cs(3) : >>> delete_maybe.txt, hello_world.txt, test.txt ,
c:UsersHPCAppDataLocalTemp1n43jzgm.0.cs(4) : }
At c:UsersHPCDocumentsTask Scriptsgrab_sql_scripts.ps1:35 char:1
+ Add-Type -TypeDefinition $HereString
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidData: (Microsoft.Power...peCompilerError:AddTypeCompilerError) [Add-Type], Exception
+ FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

Add-Type : c:UsersHPCAppDataLocalTemp1n43jzgm.0.cs(4) : Type or namespace definition, or end-of-file expected
c:UsersHPCAppDataLocalTemp1n43jzgm.0.cs(3) : delete_maybe.txt, hello_world.txt, test.txt ,
c:UsersHPCAppDataLocalTemp1n43jzgm.0.cs(4) : >>> }
At c:UsersHPCDocumentsTask Scriptsgrab_sql_scripts.ps1:35 char:1
+ Add-Type -TypeDefinition $HereString
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidData: (Microsoft.Power...peCompilerError:AddTypeCompilerError) [Add-Type], Exception
+ FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

Add-Type : Cannot add type. Compilation errors occurred.
At c:UsersHPCDocumentsTask Scriptsgrab_sql_scripts.ps1:35 char:1
+ Add-Type -TypeDefinition $HereString
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidData: (:) [Add-Type], InvalidOperationException
+ FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand

我在网上找不到很多关于这个问题的文档。有人知道这里发生了什么吗?如果没有,有人知道另一种方法来尝试我想要实现的目标吗?

谢谢!

根据C#语言规范,

enum成员名称必须是有效的标识符s。

有效的标识符不能包含.,只允许使用连接符(即_(。

因此,要么完全省略扩展:

"$($file -replace '..*$'),"

或将.替换为_:

"$($file -replace '.','_'),"

或者更新你的帖子,解释你试图通过基于文件名动态编译枚举类型来实现什么,也许我们可以向你展示一个更好的选择:(

最新更新