powershell - 您不能对空值表达式调用方法吗?

标签 powershell

我正在尝试输入“名称”并找到空格,以便我可以找到输入的名字和姓氏的第一个和最后一个字母。但它告诉我“你不能在空值表达式上调用方法。”帮忙?

$name = Read-Host "Please enter the zip of person $count"
$length = $name.Length
$name = $name.split(" ")
write-host $name[0]

最佳答案

您对帖子进行了重大更改。以前是:

$name = Read-Host "Please enter the name of person $count"
$length = $name.Length

$pos = $name.IndexOf('\s')
print $pos

让我们忽略 $length 行,因为您不使用它。看起来您正在尝试使用正则表达式分割第一个空格。您正在使用 .IndexOf() ,如果您检查重载,将会看到它需要字符串或字符。不是惊天动地,但重点是它正在寻找字符串文字并且不支持正则表达式。考虑以下陈述

PS C:\Users\Cameron> "John Smith".IndexOf('\s')
-1

PS C:\Users\Cameron> "John\sSmith".IndexOf('\s')
4

由于未找到字符串 \s,第一个返回 -1。然后我们将该字符串放在 John 和 Smith 之间,由于字符串 literal 匹配,现在我们得到了正返回。

您可能想要做的是使用 -split ,我基于您原来的问题和编辑。 -split 支持正则表达式。

PS C:\Users\Cameron> $name = "John        Smith"

PS C:\Users\Cameron> ($name -split '\s+')[0]
John

第二行代码的作用是将字符串$name拆分为空白。我们返回第一个元素,即“John”。第二个未显示,因为它应该是显而易见的,是“Smith”。这两个元素都没有尾随或前导空格(仅基于此示例。里程将根据其他字符串而有所不同。)

此外,命令printOut-Printer 的别名。怀疑您的意思是该命令,并且很可能正在寻找(如 Dane Boulton 建议的那样)Write-HostWrite-Output。注意:查找它们以了解重要的区别。前者写入控制台,而梯形图写入输出流。

最后一个好的猜测是,该错误是由调用 $name.IndexOf('\s')$name 为 null 引起的。也易于模拟。

PS C:\Users\Cameron> $something = $null

PS C:\Users\Cameron> $something.Method()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $something.Method()
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

关于powershell - 您不能对空值表达式调用方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997425/

相关文章:

azure - 如何扩展powershell数组中的对象值

powershell - 使 arraylist 上的 select -unique 返回 arraylist 而不是字符串

powershell - 使用 PowerShell SOAP 的 HP Warranty Lookup

powershell - 安装了哪个版本的 XPath

powershell - Azure Powershell : Restoring a blob snapshot to a different VM

c++ - 在C++中运行powershell脚本时如何隐藏按任意键继续

powershell - 根据Get-AdUser的结果设置AD用户的UPN

powershell - 在Powershell中比较两个文件时,比较对象的输出是什么意思

powershell - 使用 PowerShell 添加到 IIS 的绑定(bind)而不覆盖现有绑定(bind)

powershell - 找不到接受参数 'Files\'的位置参数