【问题标题】:PowerShell call operator with argument带参数的 PowerShell 调用运算符
【发布时间】:2018-10-04 16:10:42
【问题描述】:

对不起,我编辑了我的帖子,因为你没有所有信息。 此脚本的目标是启动另一个带有提升权限的参数的脚本

我这样调用脚本:

./myscript.ps1 "ScriptName.ps1" "Argument1" "Argument2"

这是我的整个脚本(myscript.ps1):

# ELEVATED SCRIPT
$ScriptName = $args[0]
$Argument1 = $args[1]
$Argument2 = $args[2]

If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
  # Relaunch as an elevated process:
  Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
  exit
}
# Now running elevated so launch the script:
& $ScriptName $Argument1 $Argument2
Pause
# This function allows me to see variables content
function Pause ($Message="Press any key to continue…")
{
Write-Host -NoNewLine $Message
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host “”
}

此行的变量为空:

& $ScriptName $Argument1 $Argument2

如果我在脚本顶部进行更改,则此脚本有效:

$ScriptName = "mycommand.exe"
$Argument1 = "something"
$Argument2 = "something_else"

我希望这次足够清楚。

【问题讨论】:

  • 您是否收到任何错误消息或代码输出?
  • $arg[0] -> $args[0]
  • 我的帖子有错误。它是 args[0] 而不是 arg[0]。当我在呼叫操作员“&”之前进行写入主机 $mycommand 时,我有一个结果。但是在 Call Operato "&" 之后,$mycommand 为空。
  • 那么请edit您的帖子并更正那个错字。当您的问题未反映您实际拥有的代码时,我们无法为您提供帮助。
  • 另外,$mycommand = $args[0]; & $mycommand 应该可以工作。如果它对您不起作用,则有其他问题。尝试从 CMD (powershell.exe -NoExit -NoProfile) 启动一个干净的 PowerShell 控制台,然后重试。还要检查您正在运行的文件是否确实具有您认为的内容 (cat .\script.ps1)。

标签: powershell arguments


【解决方案1】:

我已经解决了我的问题。 我停止尝试以提升的权限执行另一个脚本。 我已将脚本修改为自我提升。那么,我的变量就没有任何问题了。

非常感谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 2021-11-19
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多