I'm novice with powershell and do not understand why this process works:
$ftpFiles = Get-FTPChildItem -Session $Session -Path "/myroot" -Recurse | ForEach-Object { $_ | Add-Member -type NoteProperty -name CompareFullName -value ($_.FullName -Replace "ftp://ftp.server.com/myroot/", "") -PassThru }
And this does not work:
$ftpFiles = Get-FTPChildItem -Session $Session -Path "/myroot" -Recurse | Add-Member -type NoteProperty -name CompareFullName -value ($_.FullName -Replace "ftp://ftp.server.com/myroot/", "") -PassThru
I try to add a property (CompareFullName) to the file object with value that uses another property of the same file object (FullName). Add-Member was supposed to accept piped values. what happens in the non-working syntax is that the property is added alright but the value is null. The first syntax works OK. I would appreciate an explanation or another way to achieve my goal without using foreach-object.
$_
is an automatic variable that only has meaning within a script block that executes on each item in the pipeline. The first example works because when you pipeline to ForEach-Object, $_
is defined for the script block. The second example does not work because there is no script block so $_
is undefined. AFAIK there is no way to do this without a foreach. You need something to compute a value for each item in the pipeline and Add-Member does not accept a script block to compute a value for the members it attaches. I guess you use a ScriptProperty like so:
$ftpFiles = Get-FTPChildItem -Session $Session -Path "/myroot" -Recurse | Add-Member -type ScriptProperty -name CompareFullName -value {$this.FullName -Replace "ftp://ftp.server.com/myroot/", ""} -PassThru
but this is semantically different than what you have, since it computes the property value every time it accessed.
Depending on what you are trying to do, you could use Select-Object to pull off the useful properties for use later:
$ftpFiles = Get-FTPChildItem -Session $Session -Path "/myroot" -Recurse | select *, @{n="CompareFullName"; e={$_.FullName -replace "ftp://ftp.server.com/myroot/", ""}}
This would produce new custom objects with the same properties, and an additional property, 'CompareFullName'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With