1

我收到一个错误,我无法在空值表达式上调用方法。但是,我不确定为什么参数会导致空值。我需要第二双眼睛来看待这个并给我一些指导。

$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

首先:似乎 my("\.htm", ".txt")是显示为 null 的内容。我也试过没有\- (".htm", ".txt")- 并收到相同的结果。

第二:在语法上,我将我的行解释为move-item <path> <source-file-passed-to-function> <replacement=name-for-file> (parameters-for-replacement). 这是对这段代码在做什么的适当理解吗?

第三:我需要-literalpath在某个地方有一个参数吗?MS TechNet 和 get-help 关于参数使用的信息很少-literalpath;我无法找到与我的特定情况相关的东西。

帮助我了解我所缺少的。谢谢!

4

1 回答 1

3

在简单函数的上下文中$_没有定义。 $_仅在管道中有效。也就是说,$_表示正在沿管道传递的当前对象。

使用您当前的函数定义尝试这种方式:

function Rename-HtmlDocument([System.IO.FileInfo]$docs, $newExt) {  
    $docs | Move-Item -Dest {$_.FullName -replace '\.htm$', $newExt} 
}

您可以直接传递此函数$srcfilesDOC$srcFilesTXT变量,例如:

Rename-HtmlDocument $srcFilesDOC .doc
Rename-HtmlDocument $srcFilesTXT .txt

当然,您可以使其更通用并从 FileInfo 对象获取源扩展名,例如:

function Rename-DocumentExtension([System.IO.FileInfo]$docs, $newExt) {  
    $docs | Move-Item -Dest {$_.FullName.Replace($_.Extension, $newExt)} 
}

BTW PowerShell 的 Move-Item 命令没有您使用的参数-txtPath-docPath. 这是您创建的功能吗?

于 2013-01-10T15:47:03.580 回答