I’m getting an error that I can’t call a method on a null valued expression. However, I’m not sure WHY the parameters are resulting in a null value. I need a second set of eyes to look at this and give me some guidance.
$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
}
And the error….
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
First: it appears that my ("\.htm", ".txt") is what’s showing up as null. I’ve tried it without the \ – (".htm", ".txt") – as well and received the same results.
Second: syntactically, I’m interpreting my line as move-item <path> <source-file-passed-to-function> <replacement=name-for-file> (parameters-for-replacement). Is that an appropriate understanding of what this code is doing?
Third: Do I need to have a -literalpath parameter in there somewhere? MS TechNet and get-help have very little information on the uses of the -literalpath parameter; I was unable to find something relevant to my particular situation.
Help me understand what I’m missing. Thanks!
In the context of a simple function
$_is not defined.$_is only valid in a pipeline. That is,$_reprensents the current object being passed down the pipeline.With your current function definition try it this way:
You can pass this function the
$srcfilesDOCand$srcFilesTXTvariables directly e.g.:Of course you could make this more generic and get the source extension from the FileInfo object e.g.:
BTW PowerShell’s Move-Item command doesn’t have the parameters you’re using
-txtPathand-docPath. Is this a function you’ve created?