我想沿着这些方向做点什么:
$prefix = "C:\Users"
function prefix-path([string[]] $paths) {
Write-Output ([System.IO.Path]::Combine(@($prefix) + $paths))
}
prefix-path(1, 2, 3, 4)
我想收到C:\Users\1\2\3\4
,但收到的是:C:\Users 1 2 3 4
。引用1
,2
等没有帮助。
我假设PowerShell由于某种原因假设我想将数组转换为String然后继续调用Combine(String)
版本,但我希望它显然可以调用Combine(params String[])
。
当我将Combine包起来时,它可以正常工作。
function wrapped-combine([string[]] $path) {
Write-Output ([System.IO.Path]::Combine($path))
}
为什么会这样?我如何正确地写prefix-path
?
答案 0 :(得分:2)
这是因为该方法需要[string[]]
,但在PowerShell中,字符串数组(或任何类型的字符串)默认为[Object[]]
。
如果你将它投射到[string[]]
它会起作用,这就是你的"包装中发生的事情"功能:
[string[]]$components = @($prefix) + $paths
[System.IO.Path]::Combine($components)