且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

嵌入Powershell脚本问题

更新时间:2023-12-05 19:21:34

我认为问题是,您希望输出文件中的文字$homepath是为了让GitBash处理它.有很多尝试逃避和处理此问题的方法,但是可以让您与上一次所做的几乎准备就绪的方法一起使用.

I think the issue is that you want the literal $homepath in your output file in order to let GitBash deal with it. Many ways to try and escape and deal with this but lets work with you last one you made that was almost ready.

add-content "${env:homepath}\.proxy\TempProxy.bat" "alias proxyon='source `"`$HOMEPATH/.proxy/proxy-switch.sh on`"'" 

唯一不同的是$HOMEPATH前面的反引号.由于PowerShell使用$来声明和引用变量,因此您需要对其进行转义(就像对引号所做的那样),以防止PowerShell对其进行插值.

The only thing that is different here is the backtick in front of $HOMEPATH. Since PowerShell uses the $ to declare and reference variables you need to escape it, like you have done with your quotes, to prevent PowerShell from interpeting it.

由于您没有名为$HOMEPATH的变量,因此该变量将在那时创建,其值为null.这就是为什么上一个示例的输出看起来像以前一样.

Since you do not have a variable called $HOMEPATH it is created at that time with the value of null. That is why your output from your last example looked the way it did.

使用格式运算符

另一种可能更容易出现的选择是使用格式运算符.如果您想将其临时存储在变量中,则可以使用它.

Another option that might have been easier on the eyes is to use the format operator. If you wanted to store it in a variable temporarily you could have this.

$content = "alias proxyon='{0}'" -f 'source "$HOMEPATH/.proxy/proxy-switch.sh on"'
add-content "${env:homepath}\.proxy\TempProxy.bat" $content

否则将是

add-content "${env:homepath}\.proxy\TempProxy.bat" ("alias proxyon='{0}'" -f 'source "$HOMEPATH/.proxy/proxy-switch.sh on"')