[英]Passing arguments to Powershell script
我有一个最多接受 3 个参数的脚本——用户名、密码和发行版。
该脚本需要以管理员身份运行,因为它会检查某些功能是否已启用并且只能以管理员身份运行。
# the command line is:
# linux-docker <username> <password> <distro>
# if no distro is specified then Debian is used.
param ([Parameter(Mandatory)]$username, [Parameter(Mandatory)]$password, $distro='Debian')
# check if we are in admin mode and switch if we aren't
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-Not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs;
Read-Host -Prompt "Failure: Press Enter to exit"
exit;
}
}
# ... rest of script
但是重新启动脚本会提示用户输入用户名和密码。 我想将 arguments 传递给提升的脚本。
我首先想到的是将$username
、 $password
和$distro
添加到Start-Process
命令。
Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $username $password $debian" -Verb RunAs;
但这会以“失败”消息退出。
所以我查看了-ArgumentList
但是死于处理该行:
Start-Process : A positional parameter cannot be found that accepts argument '-NoProfile -ExecutionPolicy Bypass -File "C:\Users\Graham Reeds\Documents\linux-docker.ps1"'.
At C:\Users\Graham Reeds\Documents\linux-docker.ps1:15 char:9
+ Start-Process powershell.exe "-NoProfile -ExecutionPolicy Byp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
Failure: Press Enter to exit:
这可能很简单,但我是 Powershell 的菜鸟。
使用-ArgumentList
参数应该有效,但对于发送到脚本的参数,您需要从 BoundParameters hash 中获取它们的名称和值:
$currentPrincipal = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
$isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (!$isAdmin) {
$argList = '-NoLogo', '-NoProfile', '-NoExit', '-ExecutionPolicy Bypass', '-File', ('"{0}"' -f $PSCommandPath)
# Add script arguments
$argList += $MyInvocation.BoundParameters.GetEnumerator() | ForEach-Object {"-$($_.Key)", "$($_.Value)"}
try {
Start-Process PowerShell.exe -WorkingDirectory $pwd.ProviderPath -ArgumentList $argList -Verb Runas -ErrorAction Stop
# exit the current script
exit
}
catch {
Write-Warning "Failed to restart script '$PSCommandPath' with runas"
}
}
# rest of the script
PS 就我个人而言,我喜欢始终对参数进行类型转换,并在可能的情况下明确说明如果不使用强制参数,则应按什么顺序给出命名:
param (
[Parameter(Mandatory = $true, Position = 0)][string] $username,
[Parameter(Mandatory = $true, Position = 1)][string] $password,
[string] $distro='Debian'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.