【发布时间】:2013-01-11 09:12:53
【问题描述】:
我收到一个错误,我无法在空值表达式上调用方法。但是,我不确定为什么参数会导致空值。我需要第二双眼睛来看待这个并给我一些指导。
$docpath = "c:\users\x\desktop\do"
$htmPath = "c:\users\x\desktop\ht"
$txtPath = "c:\users\x\desktop\tx"
$srcPath = "c:\users\x\desktop\ht"
#
$srcfilesTXT = Get-ChildItem $txtPath -filter "*.htm*"
$srcfilesDOC = Get-ChildItem $docPath -filter "*.htm*"
$srcfilesHTM = Get-ChildItem $htmPath -filter "*.htm*"
#
function rename-documents ($docs) {
Move-Item -txtPath $_.FullName $_.Name.Replace("\.htm", ".txt")
Move-Item -docpath $_.FullName $_.Name.Replace("\.htm", ".doc")
}
ForEach ($doc in $srcpath) {
Write-Host "Renaming :" $doc.FullName
rename-documents -docs $doc.FullName
$doc = $null
}
还有错误....
You cannot call a method on a null-valued expression.
At C:\users\x\desktop\foo002.ps1:62 char:51
+ Move-Item -txtPath $_.FullName $_.FullName.Replace <<<< ("\.htm", ".txt")
+ CategoryInfo : InvalidOperation: (Replace:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\users\x46332\desktop\foo002.ps1:63 char:51
+ Move-Item -docpath $_.FullName $_.FullName.Replace <<<< ("\.htm", ".doc")
+ CategoryInfo : InvalidOperation: (Replace:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
首先:我的("\.htm", ".txt") 似乎显示为空。我在没有\ - (".htm", ".txt") 的情况下也试过了,并且得到了相同的结果。
第二:从句法上讲,我将我的行解释为move-item <path> <source-file-passed-to-function> <replacement=name-for-file> (parameters-for-replacement)。这是对这段代码在做什么的适当理解吗?
第三:我需要在某个地方有一个-literalpath 参数吗? MS TechNet 和 get-help 关于-literalpath 参数的使用信息很少;我无法找到与我的特定情况相关的东西。
帮助我了解我缺少什么。谢谢!
【问题讨论】:
-
第一:
$srcpath包含 "c:\users\x\desktop\ht" 作为字符串,而不是文件列表。第二:对于您的move-item这 ->-txtpath是要移动的文件的名称,而不是路径。在你的问题中描述你的目标到底是什么。 -
第三个:
-literalpath根据您的先例问题move-item需要stackoverflow.com/a/14259748/520612 -
目标:我正在尝试将一批文件从 *.foo 重命名为 *.bar。重命名必须是脚本中的函数。该脚本已经设置了需要传递给函数的路径变量。
-
尝试关注@keithill 的回答,它会以正确的方式出现!
标签: powershell nullreferenceexception file-rename