我花了一些时间找出 Powershell 脚本的正确语法。然而最终这是一种反复试验的方法,我想知道为什么下面的语法不起作用。
该脚本以提升模式启动新的 Powershel 并设置环境变量。这是摘录:
$x = "NewValue"
$arguments = "-NoExit", "-command", "&{ [Environment]::SetEnvironmentVariable(`"MyVar1`", `"$x`", [EnvironmentVariableTarget]::Machine) }"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Run Code Online (Sandbox Code Playgroud)
如果我只是打印出变量$arguments
,它就是我所期望的一个数组:
-NoExit
-command
&{ [Environment]::SetEnvironmentVariable("MyVar1", "NewValue", [EnvironmentVariableTarget]::Machine) }
Run Code Online (Sandbox Code Playgroud)
然而,在子 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 ... …
Run Code Online (Sandbox Code Playgroud) 我正在尝试在cmd中使用以下Powershell脚本。这是一个简单的例子:
$path = "c:\"
cd $path
ls
Run Code Online (Sandbox Code Playgroud)
一些多行且带引号的PowerShell脚本。
我阅读了这篇文章以及@Alex在这篇文章中的回答,但是;
在它们之间放置多行并没有用:
C:\ Users \ abcd> powershell“&c:\; ls” &:术语'c:\'不被识别为cmdlet,函数, 脚本文件或可操作程序。检查名称的拼写,或者 包含路径,请确认路径正确,然后重试。 行:1字符:2 +&c:\; ls + ~~~ + CategoryInfo:ObjectNotFound:(c:\:String)[],CommandNotFoundException + FullyQualifiedErrorId:CommandNotFoundException
PS:我的实际任务是运行以下命令(我在上面提供了琐碎的任务,因为并非每个人都有数据库)。
$tabular_server = "abc_123\Tabular"
[Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server = New-Object Microsoft.AnalysisServices.Server
$server.connect($tabular_server)
$db = $server.Databases.Item("db_name")
$db.Process("ProcessClear")
$db.Process("ProcessDefault")
$server.Disconnect()
Run Code Online (Sandbox Code Playgroud)