Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 子串函数don';不能使用变量_Powershell_Directory_Substring_Get Childitem - Fatal编程技术网

Powershell 子串函数don';不能使用变量

Powershell 子串函数don';不能使用变量,powershell,directory,substring,get-childitem,Powershell,Directory,Substring,Get Childitem,我需要字符串的前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 = G

我需要字符串的前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)
错误:

方法调用失败,因为[Selected.System.IO.FileInfo]没有 不包含名为“Substring”的方法。在Z:\skcript\uebung1.ps1:16 字符:1 +$test.子字符串(0,3) + ~~~~~~~~~~~~~~~~~~~~ +CategoryInfo:InvalidOperation:(子字符串:字符串)[],RuntimeException +FullyQualifiedErrorId:MethodNotFound


错误的原因是什么?

您的
$test
变量引用的不是
字符串
,而是由返回实例的
名称
状态
属性组成的对象。在这个合成的对象上(就这一点而言,
FileInfo
上也没有),因此出现了错误。要获取文件名,您需要访问,例如

$test.Name.Substring(0, 3)
或者,如果您只需要
名称
属性(不确定
状态
来自何处),则可以使用仅检索一个值

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

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

谢谢您的反馈$folderinput是错误的。只有$folderinput是正确的。用例是:从1月1日到12月12日的子文件夹。感谢您的反馈$folderinput是错误的。只有$folderinput是正确的。用例是:从1(一月)到12(十二月)命名的子文件夹。从我将文件保存到文件夹1、2或3等的月份开始,我的计划是将月份(1到12)作为字符串写入变量中。然后我选择路径“Z:\Home\Chronos\”并添加月份(1或2等)我不清楚我的代码建议是否解决了您的问题,或者是否有助于解决您的问题。此外,您问题中的代码注释说,第二个代码段有效,但第一个代码段无效。因此,只有第一个代码段会引发列出的错误?似乎它们都应该这样做,因为正如我所提到的,它们都非常相似。如果您进行更新,将会有所帮助带这些附加细节和变量更正的问题。我理解你所说的,关于FSO,而不是字符串。我只需要一个解决方案,用数字捕捉月份,然后我将其用作字符串。我尝试使用字符串。但结果不是我想要的。使用字符串(“m”)获取日期不要给我这个月的数字。我能提供的关于所提供信息的唯一进一步建议是,如果
$datum
包含
DateTime
(例如
$datum=Get Date
$datum=[DateTime]::今天)
那么
$datum.Month
是访问Month组件的正确方法。但是,您没有显示
$datum
是如何设置的。我认为您确实需要在问题中提供答案,因为这里有太多的未知数,除了猜测之外,无法进行任何操作。您在这些注释中描述的问题似乎与我所描述的问题不同问题也是如此。