我正在使用版本5.1的从目录中读取文件,然后希望将这些文件名添加到Enum以供以后使用。我找到了一种通过C#通过HereString传递代码的方法。
#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:\Users\HPC\AppData\Local\Temp\1n43jzgm.0.cs(3) : } expected
c:\Users\HPC\AppData\Local\Temp\1n43jzgm.0.cs(2) : {
c:\Users\HPC\AppData\Local\Temp\1n43jzgm.0.cs(3) : >>> delete_maybe.txt, hello_world.txt, test.txt ,
c:\Users\HPC\AppData\Local\Temp\1n43jzgm.0.cs(4) : }
At c:\Users\HPC\Documents\Task Scripts\grab_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:\Users\HPC\AppData\Local\Temp\1n43jzgm.0.cs(4) : Type or namespace definition, or end-of-file expected
c:\Users\HPC\AppData\Local\Temp\1n43jzgm.0.cs(3) : delete_maybe.txt, hello_world.txt, test.txt ,
c:\Users\HPC\AppData\Local\Temp\1n43jzgm.0.cs(4) : >>> }
At c:\Users\HPC\Documents\Task Scripts\grab_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:\Users\HPC\Documents\Task Scripts\grab_sql_scripts.ps1:35 char:1
+ Add-Type -TypeDefinition $HereString
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Add-Type], InvalidOperationException
+ FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand我在网上找不到很多关于这个问题的文档。有人知道这里发生了什么吗?如果没有,有没有人知道另一种方法来尝试我想要达到的目标?
谢谢!
发布于 2020-07-20 13:56:06
根据enum语言规范,_identifier_s成员名称必须是有效的C#。
有效标识符不能包含.,唯一允许的标点符号是连接器(即。_)。
因此,要么完全忽略扩展:
"$($file -replace '\..*$'),"..。或将.替换为_
"$($file -replace '\.','_'),"..。或者通过基于文件名动态编译枚举类型来更新您的文章来解释您想要实现的目标,也许我们可以向您展示一个更好的选择:)
https://stackoverflow.com/questions/62996717
复制相似问题