我花了一些時間搞清楚Powershell腳本的正確語法。但最終它是試錯法,我想知道爲什麼下面的語法不起作用。Powershell - 轉義字符串傳遞給子進程
該腳本以提升模式啓動新的Powershel並設置環境變量。下面是摘錄:
$x = "NewValue"
$arguments = "-NoExit", "-command", "&{ [Environment]::SetEnvironmentVariable(`"MyVar1`", `"$x`", [EnvironmentVariableTarget]::Machine) }"
Start-Process powershell -Verb runAs -ArgumentList $arguments
如果我剛打印出來的變量$arguments
,它是一個數組,因爲我所期望的:
-NoExit
-command
&{ [Environment]::SetEnvironmentVariable("MyVar1", "NewValue", [EnvironmentVariableTarget]::Machine) }
然而,在孩子PowerShell中的雙引號以某種方式和失蹤食用。爲什麼?它預期的行爲?它輸出:
At line:1 char:42
+ &{ [Environment]::SetEnvironmentVariable(MyVar1, NewValue, [EnvironmentVariableT ...
+ ~
Missing ')' in method call.
At line:1 char:42
+ &{ [Environment]::SetEnvironmentVariable(MyVar1, NewValue, [EnvironmentVariableT ...
+ ~~~~~~
Unexpected token 'MyVar1' in expression or statement.
At line:1 char:48
+ &{ [Environment]::SetEnvironmentVariable(MyVar1, NewValue, [EnvironmentVariableT ...
+ ~
Missing argument in parameter list.
At line:1 char:2
+ &{ [Environment]::SetEnvironmentVariable(MyVar1, NewValue, [EnvironmentVariableT ...
+ ~
Missing closing '}' in statement block.
At line:1 char:96
+ ... arget]::Machine) }
+ ~
Unexpected token ')' in expression or statement.
At line:1 char:98
+ ... get]::Machine) }
+ ~
Unexpected token '}' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
我的環境:
> $PSVersionTable
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.42000
BuildVersion 6.3.9600.17400
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
============================== =================================
作爲參考,這裏的工作版本使用單引號而不是雙引號(我還刪除了-NoExit參數,它僅用於調試):
$x = "NewValue"
$arguments = "-command", "&{ [Environment]::SetEnvironmentVariable('MyVar1', `'$x`', [EnvironmentVariableTarget]::Machine) }"
Start-Process powershell -Verb runAs -ArgumentList $arguments
''$參數= 「-noexit」, 「指令」, 「'」 &{[環境] :: SetEnvironmentVariable方法(\''MyVar1 \'「,\'」$ x \'「,[EnvironmentVariableTarget] :: Machine)}'」「'' – PetSerAl
@PetSerAl你爲什麼要回答?作爲評論它是混亂。 – JPBlanc
@JPBlanc恕我直言,它需要的不僅僅是一段代碼,而是一個正確的答案。 – PetSerAl