Home > Blockchain >  Powershell: stripping a file name sometimes doesn't work
Powershell: stripping a file name sometimes doesn't work

Time:12-24

I have a Powershell script that is called from the command line.

script.ps1 "\\testfolder" "testinput" "xml" "xml2html.xsl" "testfile" "css"

The script uses these command line arguments:

param([string]$publish_folder, [string]$input_filename, [string]$input_ext, [string]$transformation_filename, [string]$output_filename, [string]$output_ext)

$input_filename and $output_filename may be a full path filename, the filename only or the filename without extension.

$inputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($input_filename)
$inputPath=$publish_folder "\" $inputFileNameOnly "." $input_ext 
$outputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($output_filename) 
$outputPath=$publish_folder "\" $outputFileNameOnly "." $output_ext

When I run this locally, it works. Output path:

\\testfolder\testfile.css

When I run the same script in an AWS instance, it fails. $inputpath is calculated correctly, but Output path becomes:

\\testfolder\.

so both $output_filename and $output_ext are empty.

The paths are longer than \\testfolder\, but not long enough to cause trouble (about 150 characters). Total length of the arguments doesn't seem to be a problem either.

What could be causing this problem?

CodePudding user response:

$outputPath="$publish_folder "\" 

Looks like you broke your concatenation here. Double-quote before $publish_folder.

Edit: Can also be written like this if you don't want to concatenate ( )

$outputPath="$publish_folder\$outputFileNameOnly.$output_ext"

Anything in double-quotes should be expanded correctly.

CodePudding user response:

I set up your script as a function and passed those parameters.

function rename {
    param(
        [string]$publish_folder, 
        [string]$input_filename,
        [string]$input_ext, 
        [string]$transformation_filename,
        [string]$output_filename, 
        [string]$output_ext
    )

    $inputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($input_filename)
    $inputPath = $publish_folder "\" $inputFileNameOnly "." $input_ext 
    $outputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($output_filename) 
    $outputPath = $publish_folder "\" $outputFileNameOnly "." $output_ext
    return $outputPath
}

Output is this...
\\\\testfolder\\\\testfile.css

Try passing $publish_folder without ending backslash

Edit: Sorry about formatting. Need some forum practice. =)

  • Related