Powershell 中的前缀赋值运算符

Prefix Assignment Operator in Powershell

所以 powershell(和大多数语言)有一个 assignment by addition operator 通过将新字符串添加到原始字符串的尾部来处理字符串

例如这个:

$targetPath += "\*"

将执行与此相同的操作:

$targetPath = "$targetPath\*"

是否有一个运算符可以做同样的事情,但通过为当前字符串添加前缀?

当然,我可以执行以下操作,但我正在寻找更简洁的内容

$targetPath = "Microsoft.PowerShell.Core\FileSystem::$targetPath"

PowerShell 没有 - 但 .NET [string] 类型具有 Insert() 方法:

PS C:\> "abc".Insert(0,"xyz")
xyzabc

虽然你仍然不能简化分配,它会变成:

$targetPath = $targetPath.Insert(0,'Microsoft.PowerShell.Core\FileSystem::')

或者,创建一个为您完成此操作的函数:

function Prepend-StringVariable {
    param(
        [string]$VariableName,
        [string]$Prefix
    )

    # Scope:1 refers to the immediate parent scope, ie. the caller
    $var = Get-Variable -Name $VariableName -Scope 1
    if($var.Value -is [string]){
        $var.Value = "{0}{1}" -f $Prefix,$var.Value
    }
}

并在使用中:

PS C:\> $targetPath = "C:\Somewhere"
PS C:\> Prepend-String targetPath "Microsoft.PowerShell.Core\FileSystem::"
PS C:\> $targetPath
Microsoft.PowerShell.Core\FileSystem::C:\Somewhere

尽管我通常建议不要使用这种模式(除非必要,否则写回祖先作用域中的变量)