即使长度为 1,也返回正确的 .length [英] Returning correct .length even though length is 1

查看:43
本文介绍了即使长度为 1,也返回正确的 .length的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我做一个

$services = Get-Service
$services.length

我获得了 126 项服务.但是如果我指定一项服务

I get 126 services. But if I specify one service

$services = Get-Service -Name vds
$services.length

我一无所获.这弄乱了我在脚本中执行的循环.即使长度为 1,我如何从 .length 返回正确的数字?

I get nothing. This messes up loops I do in my script. How do I return the correct number from .length even though the length is 1 ?

使用普通字符串这很容易,我只需指定为数组:

With normal strings this is easy, I just specify as array:

$myarray = ,"one","two","three"
$myarray.length

将返回 3,并且

$myarray = ,"one"
$myarray.length

将返回 1..

如何获得正确的长度返回?

推荐答案

你一无所获的原因是,当你按名称请求 1 个服务时,$services 不再是一个数组.您可能必须创建数组并将服务分配给元素 0.

The reason you get nothing is because $services is no longer an array when you request 1 service by name. You'll likely have to create the array and assign the service to element 0.

这对我有用...

$services = @(Get-Service -Name vds)

这篇关于即使长度为 1,也返回正确的 .length的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆