我的脚本从TFS读取一个路径,并向其中添加一个字符串,但在需要验证路径是否包含一个符号之前。
Example1:这就是路径,在本例中,我需要添加'/database/‘
$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22Example2:我只需要添加“数据库/”
$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22/Example3:我需要加上/
$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22/database我们的目标是继续使用path/database/所以我需要先检查路径,然后添加或删除‘数据库’字符串--任何人都可以帮助我吗?
发布于 2022-05-26 18:59:47
如果我正确地理解了这个问题,您需要检查来自TFS的路径是否以正斜杠结尾,这样您就知道应该追加什么,因此您可以使用这样的小助手函数:
function Join-TFSPath {
[CmdletBinding()]
param (
[parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[string] $Path,
[parameter(Mandatory = $false, Position = 1)]
[string[]] $ChildPath,
[char]$Separator = '/'
)
if ($ChildPath.Count) {
"{0}$separator{1}$Separator" -f $Path.TrimEnd("\/"),
(($ChildPath | ForEach-Object { $_.Trim("\/") } |
Where-Object { $_ -match '\S' }) -join $Separator)
}
else {
"{0}$separator" -f $Path.TrimEnd("\/")
}
}
# test if you need to add `database` or not
$tfsPath = '$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22/database'
$folder = 'database'
if (($tfsPath.TrimEnd("\/") -split '[\\/]')[-1] -ne $folder) {
# use the function adding the $folder as ChildPath
Join-TFSPath -Path $tfsPath -ChildPath $folder
}
else {
# use the function without specifying the ChildPath so it will only ensure it
# ends with the chosen (or in this case default) separator character
Join-TFSPath -Path $tfsPath
}根据您的评论,您也许可以使用更专用的助手函数,例如:
function Append-TFSPath {
[CmdletBinding()]
param (
[parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[string] $Path,
[parameter(Mandatory = $false, Position = 1)]
[string] $ChildPath = 'database',
[char]$Separator = '/'
)
$Path = $Path -replace '[\\/]+$' # trim off final slash(es)
$ChildPath = $ChildPath -replace '^[\\/]|[\\/]$' -replace '\\', $Separator
if ([string]::IsNullOrWhiteSpace($ChildPath) -or ($Path -replace '\\', $Separator) -like "*$ChildPath") {
"{0}$separator" -f $Path
}
else {
"{0}$separator{1}$Separator" -f $Path, $ChildPath
}
}然后,只需按收到的方式发送路径到函数,它就会返回您想要的路径。
$tfsPath = '$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22/database'
$folder = 'V8.6.22/database'
Append-TFSPath -Path $tfsPath -ChildPath $folder
# because 'database' is the default value for the ChildPath parameter, you can leave that out:
# Append-TFSPath -Path $tfsPath测试案例:
Append-TFSPath -Path '$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22'
Append-TFSPath -Path '$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22/'
Append-TFSPath -Path '$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22/database'
Append-TFSPath -Path '$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22/database/'都会返回$/Idu Client-Server/CoreBranches/V6.4/Patches/V8.6.22/database/吗
https://stackoverflow.com/questions/72395012
复制相似问题