PowerShell将CSV值(PscustomObject)的列表转换为整数

发布于 2025-02-06 10:37:06 字数 458 浏览 3 评论 0原文

我使用 import-csv 将CSV文件读取到变量中。现在,当我尝试打印某个属性的所有值的列表时,我可以通过 getType()看到这些不是整数值,而是“ pscustomobjects” 。如何将所有这些值转换为整数?我需要进行操作,例如 sort-object 等。

我尝试在其他线程中找到一些类型,例如:

[int]($ myArray | select -expandproperty级别)

但是它们可以工作,因为我会发现一个错误,即无法将pscustomobject转换为int或其他任何东西。我什至不知道这个对象应该是什么,我的意思是我可以看到列表包含数字,所以为什么它们要么串起或整数……有时Powershell会让我发疯。

感谢您的帮助

i read a csv file into a variable using Import-CSV. Now when I try to print a list of all values of a certain property, I can see through GetType() that these are not Integer values but rather "PSCustomObjects". How can i convert all of these values into integer? I need to do manipulations like Sort-Object etc.

I tried doing some typecasts i found in other threads like so:

[int]($MyArray | select -ExpandProperty Level)

but they arent working because I get an error that its not possible to convert from pscustomobject to int or whatever. I don't even know what this object is supposed to be, I mean i can see the list contains numbers, so why arent they either string or integer...Sometimes powershell is driving me crazy.

Thanks for the help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莳間冲淡了誓言ζ 2025-02-13 10:37:11

int> intArray的正确铸件是:

[int[]]($MyArray | select -ExpandProperty Level)

您可以通过使用成员访问

[int[]] $MyArray.Level

枚举> foreach 方法,它具有用于类型铸造的过载:

$MyArray.Level.ForEach([int])

在这种情况下,我们没有指定数组类型,因为foreach将铸造的类型应用于每个元素。如果您想链条更多的方法,这可能很方便:

$MyArray.Level.ForEach([int]).Where{ $_ -gt 2 }

要遵循声明的执行顺序,我们可以从左到右线性地读取它。与阵列铸件进行比较,由于括号,这更难遵循:

([int[]] $MyArray.Level).Where{ $_ -gt 2 }

The correct cast to an array of int is:

[int[]]($MyArray | select -ExpandProperty Level)

You can make this shorter by using member access enumeration:

[int[]] $MyArray.Level

Another way is to use the intrinsic ForEach method, which has an overload for type casting:

$MyArray.Level.ForEach([int])

In this case we don't specify an array type, because ForEach applies the type cast to each element individually. This might be handy if you want to chain more methods like this:

$MyArray.Level.ForEach([int]).Where{ $_ -gt 2 }

To follow the execution order of the statement we can linearly read it from left to right. Compare with an array cast, which is more difficult to follow because of the parentheses:

([int[]] $MyArray.Level).Where{ $_ -gt 2 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文