子字符串函数不适用于变量

Substring Function don't work with a variable

我需要字符串的前 3 个字节。我的代码出错。

# This Code don't work
$folderoutput="Z:\Home\Chronos\" + $datum.Month;
$test = Get-ChildItem -Path $folderinput| select name, state -last 1
$test.Substring(0,3)

# This Code work
$folderoutput="Z:\Home\Chronos\" + "11"
$test = Get-ChildItem -Path $folderinput| select name, state -last 1
$test.Substring(0,3)

错误:

Method invocation failed because [Selected.System.IO.FileInfo] does not contain a method named 'Substring'. At Z:\skript\uebung1.ps1:16 char:1 + $test.Substring(0,3) + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (Substring:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound

错误原因是什么?

您的 $test 变量引用的不是 String,而是一个由返回的 FileInfo instance. There is no Substring method on this composed object (nor on a FileInfo, for that matter), hence the error. To get the name of the file you need to access the Name propertyNameState 属性组成的对象,就像这样。 ..

$test.Name.Substring(0, 3)

或者,如果您只想要 Name 属性(不确定 State 来自哪里),您可以使用 -ExpandProperty parameter 来仅检索那个值。 ..

$test = Get-ChildItem -Path $folderinput| select -ExpandProperty name -last 1
$test.Substring(0, 3)

至于为什么一个片段有效而另一个无效,这还不清楚。两者唯一的区别是$folderoutput的值没有被使用;在下一行中,您将 $folderinput 传递给 Get-ChildItem。您确定 $datum 已设置并具有 Month 属性 吗?