Powershell中的前缀分配运算符
因此,powershell(和大多数语言)都有一个通过将新字符串添加到原始字符串尾部来处理字符串的方法 例如:Powershell中的前缀分配运算符,powershell,syntax,Powershell,Syntax,因此,powershell(和大多数语言)都有一个通过将新字符串添加到原始字符串尾部来处理字符串的方法 例如: $targetPath += "\*" 将执行与此相同的操作: $targetPath = "$targetPath\*" 是否有一个运算符可以执行相同的操作,但只需在当前字符串前面加前缀 当然,我可以做到以下几点,但我正在寻找更简洁的东西 $targetPath = "Microsoft.PowerShell.Core\FileSystem::$targetPath" Powe
$targetPath += "\*"
将执行与此相同的操作:
$targetPath = "$targetPath\*"
是否有一个运算符可以执行相同的操作,但只需在当前字符串前面加前缀
当然,我可以做到以下几点,但我正在寻找更简洁的东西
$targetPath = "Microsoft.PowerShell.Core\FileSystem::$targetPath"
PowerShell没有-但是.NET
[string]
类型具有以下方法:
但是,您仍然无法设置该分配的快捷方式,它将变成:
$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
尽管我通常不推荐这种模式(除非必要,否则写回祖先作用域中的变量)
PS C:\> $targetPath = "C:\Somewhere"
PS C:\> Prepend-String targetPath "Microsoft.PowerShell.Core\FileSystem::"
PS C:\> $targetPath
Microsoft.PowerShell.Core\FileSystem::C:\Somewhere