Reputation: 2115
I've got a Powershell script which is called with an argument that contains a file name. I want to strip the extension from the filename. This is the script:
param([string]$input_filename)
$inputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($input_filename) | Out-file "myfile.log" -Append
Write-Output "input filename without extension: " $inputFileNameOnly | Out-file "myfile.log" -Append
When I run the file: .\myscript.ps1 "E:\Projectdata\Test book.html"
I can see that the call [System.IO.Path]::GetFileNameWithoutExtension($input_filename)
works: the first line in my log file is "Test book".
But nothing is placed after "input filename without extension: ". No value is assigned to variable $inputFileNameOnly.
What am I doing wrong here? There doesn't seem to be a type mismatch: [System.IO.Path]::GetFileNameWithoutExtension
outputs a string.
I'm using Powershell 5 in Windows 10.
Upvotes: 0
Views: 231
Reputation: 1884
You are a little to fast with your pipes:
$inputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($input_filename) | Out-file "myfile.log" -Append
Those are two steps in one:
[System.IO.Path]::GetFileNameWithoutExtension($input_filename) | Out-file...
will get your value and write it to a file. However this action will not provide any output that can be captured in $inputFileNameOnly
. $inputFileNameOnly
is $Null
.
Instead save the filename first in a variable and use that for the Out-File
:
$inputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($input_filename)
Out-file -InputObject $inputFileNameOnly -FilePath "myfile.log" -Append
Some cmdlets that don't provide output to the piple have the parameter -PassThru
to force them sending something into the pipeline. Unfortunately Out-File
doesn't.
Upvotes: 1