我正在尝试在powershell中组合字符串以生成文件路径。我正在学习基础知识,并将这种语法放在一起
$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)\
}
但是当我Write-Host
时,文件路径中有一个空格。输出是
E:\Main Folder\ 2016 \
如何删除空格?我尝试使用Trim()
运算符,但空格仍然存在。
答案 0 :(得分:1)
不要破坏你的泡泡,但已经有一个cmdlet和.Net方法来组合路径:
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)