[英]How do you resolve special folders in path strings in PowerShell?
在Windows命令提示符中,特殊文件夹的解析如下:
但是,在powershell中,似乎无法解析这些文件夹:
考虑以下字符串:
$myfile = "%temp%\\myfolder\\myfile.txt"
如何将其用作PowerShell函数的参数(例如: Remove-Item
),并让PowerShell正确解析特殊文件夹,而不是将其按字面意义放在当前工作目录之前?
我正在使用来自外部配置文件的标准Windows路径符号处理字符串,例如:
config.json:
{
"some_file": "%TEMP%\\folder\\file.txt"
}
myscript.ps1:
$config = Get-Content -Raw -Path "config.json" | ConvertFrom-Json
Remove-Item -path $config.some_file -Force
注意:由于任何Windows特殊文件夹都可以出现在这些字符串中,因此,我宁愿避免这种可怕的查找替换黑客
$config.some_file = $config.some_file -replace '%TEMP%' $env:temp
如果您不介意一些性能问题
$resolvedPathInABitHackyWay = (cmd /c echo "%TEMP%\\\\folder\\\\file.txt")
实际上,这将使您%TEMP%由cmd本身解决。
您可以从env:\\
驱动器中获取所有env变量,并使用该变量为您的find-replace操作构造一个简洁的regex模式,然后将Regex.Replace()
方法与匹配评估器一起使用:
$vars = Get-ChildItem env:\ |ForEach-Object {[regex]::Escape($_.Name)}
$find = "%(?:$($envNames -join '|'))%"
[regex]::Replace($config.some_file, $find, {param([System.Text.RegularExpressions.Match]$found) return (Get-Item "env:\$($found.Groups[1])").Value},'IgnoreCase')
您可以使用以下方法将其展开为完整路径:
[System.Environment]::ExpandEnvironmentVariables("%TEMP%\\myfolder\\myfile.txt")
c:\users\username\AppData\Local\Temp\\myfolder\\myfile.txt
双反斜杠\\\\
也不是PowerShell的东西, \\
也不是PowerShell字符串中的特殊字符-但路径中的双反斜杠似乎确实有效。
文档: https : //msdn.microsoft.com/zh-cn/library/system.environment.expandenvironmentvariables.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.