将 Selected.System.String 转换为 System.String

Convert Selected.System.String to System.String

在 Powershell 中,我这样调用 [io.path]::GetExtension(..):

...| Select-Object {[io.path]::GetExtension($_)}

我得到以下输出:

[io.path]::GetExtension($_)
---------------------------






.dll                       
.dll                       
.dll                       
.dll                       
.dll                       
.dll                       
.dll                       
.dll                       
.dll                       
.dll

(注意某些输入缺少扩展名,因此它们的输出为空)

然后通过管道传输到 "Get-Member" 产生:

   TypeName: Selected.System.String

Name                        MemberType   Definition                                
----                        ----------   ----------                                
Equals                      Method       bool Equals(System.Object obj)            
GetHashCode                 Method       int GetHashCode()                         
GetType                     Method       type GetType()                            
ToString                    Method       string ToString()                         
[io.path]::GetExtension($_) NoteProperty System.String [io.path]::GetExtension($_)=

但是我想要 System.String,而不是 Selected.System.String, 因为我想分组-Object,我(显然)无法对 Selected.System.String 进行分组,因为它没有实现 IComparable.

调用“.ToString()”不会引发错误,但不会将其转换为字符串。

如何生成字符串,或将输出转换为字符串?

要将输出打印为字符串,试试这个:

'C:\x.ini','C:\y.ini' | % { [io.path]::GetExtension($_) } 

.ini

.ini

TypeName: System.String

在这种情况下,% 或 Foreach-Object 将 运行 每个输入的命令,生成您需要的输出。 Select-Object 实际上会创建一个包含输出的选择对象。打印此对象内容的方法有很多种,但使用 Foreach-Object 可能是最简单的方法。

如果您要处理字符串,我建议您只使用正则表达式:

$Paths -replace '.*?(\.\w+$)', ''

这将为您 return 一个 [System.String[]] 对象,其扩展形式为 .exe