所以powershell(和大多数语言)有一个赋值加法运算符,通过将新字符串添加到原字符串的尾部来处理字符串
例如:
$targetPath += "*"
的作用与下面的相同:
$targetPath = "$targetPath*"
是否有一个操作符可以做同样的事情,但通过前缀当前字符串?
当然,我可以这样做,但我正在寻找一些稍微简洁的
$targetPath = "Microsoft.PowerShell.CoreFileSystem::$targetPath"
PowerShell没有-但是。net [string]
类型有Insert()
方法:
PS C:> "abc".Insert(0,"xyz")
xyzabc
你仍然不能快捷分配,它会变成:
$targetPath = $targetPath.Insert(0,'Microsoft.PowerShell.CoreFileSystem::')
或者,创建一个函数来帮你完成:
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.CoreFileSystem::"
PS C:> $targetPath
Microsoft.PowerShell.CoreFileSystem::C:Somewhere
尽管我通常不建议使用这种模式(除非必要,否则要写回祖先作用域中的变量)