Home > other >  espace content of variable for cd
espace content of variable for cd

Time:11-28

I am using Powershell, I loop through files and create a folder with each file's name to put some data there.

$files = @("[som]video.mkv")
$tmp_location = "." 
# to reproduce just do it on files with a filename like [somen_id]restofname.ext 
foreach ($file in $files){
    $base_input = ([io.fileinfo]$file).basename
    # base input may be a file called: [somen_id]restofname.ext 
    $tmp_dir = "$tmp_location/$base_input"
    mkdir $tmp_dir  # this line works and the directory is created
    # do some stuff first before cd
    cd $tmp_dir #this does not work

}

cd fails to handle the tmp_dir variable when it has special characters like [], but mkdir (and even rm) create/delete that directory just fine, which is a very inconsistent behavior in Powershell, I would expect it to either fail for all or work for all!

Any idea how to escape the variable such that it becomes readable to cd

(ofc in real life my array is not just 1 filename written by hand, but this example shows the error too)

Thanks

CodePudding user response:

tl;dr

Use the -LiteralPath parameter to pass paths meant to be interpreted literally (verbatim):

# "cd" is a built-in alias of "Set-Location"
# "sl" is another built-in alias
# Interactively, using PowerShell's elastic syntax, 
# you can shorten "-LiteralPath" to "-l".
# In PowerShell (Core) 7 , "-lp" is an official alias.
cd -LiteralPath $tmp_dir 

See this answer for more information.

  • Related