2

I am attempting to combine strings in powershell to generate a file path. I am learning the basics and have put together this syntax

$fileDirectory = "C:\Pics\"

foreach ($file in Get-ChildItem $fileDirectory){
    #Setting parent dir to check
    $ParentDir = "E:\Main Folder\"

    #setting param to split
    $parts =$file.Name -split '\.'

    #capturing variables
    $PictureYear = $parts[0].Trim()
    $PictureMonth = $parts[1].substring(0,3)

    #Writing To window to confirm variables are accurate
    Write-Host $PictureYear
    Write-Host $PictureMonth

    #checking if folders exist
    Write-Host $($ParentDir)$($PictureYear)\
}

But when I Write-Host there is a space in the filepath. The output is

E:\Main Folder\ 2016 \

How can I remove the space? I tried using the Trim() operator but the space still exists.

2
  • Look into Join-Path and Split-Path. Commented Feb 8, 2017 at 20:24
  • @KoryGill - thank you for pointing in the right direction! Commented Feb 8, 2017 at 20:28

1 Answer 1

2

Not to burst your bubble, but there's already a cmdlet and a .Net method to combine paths:

Join-Path -Path $ParentDir -ChildPath $PictureYear
$ParentDir | Join-Path -ChildPath $PictureYear | Join-Path -ChildPath $PictureMonth

[System.IO.Path]::Combine($ParentDir, $PictureYear, $PictureMonth)

$parts = @($ParentDir) + $parts  # array of all components    
[System.IO.Path]::Combine([string[]]$parts)
Sign up to request clarification or add additional context in comments.

1 Comment

Not bursting bubble at all! This is excellent and a wonderful example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.