使用多个命名参数以高架模式调用脚本

时间:2018-03-29 11:39:05

标签: powershell arguments

Test.ps1

Param (
    [String]$CountryCode,
    [String]$FilesPath,
    [String]$KeepassDatabase,
    [String]$KeepassKeyFile,
    [String]$EventLog,
    [String]$EventSource
)

Write-Host 'Ok' -ForegroundColor Yellow
Write-Host $PSBoundParameters
Start-Sleep -Seconds 5

目标是在提升模式下使用命名参数调用脚本。使用没有$Credential的命名参数时,它可以正常工作。弹出窗口,显示单词Ok

$StartParams = @{
    ArgumentList = "-File `"Test.ps1`" -verb `"runas`" -FilesPath `"S:\Files`" -CountryCode `"XXX`""
}
Start-Process powershell @StartParams

当我添加Credential参数时,它也会弹出,但我看不到任何内容:

$StartParams = @{
    Credential   = Get-Credential
        ArgumentList = "-File `"Test.ps1`" -verb `"runas`" -FilesPath `"S:\Files`" -CountryCode `"XXX`""
}
Start-Process powershell @StartParams

我错过了一些非常明显的东西吗?即使使用与登录用户相同的凭据,我也无法看到该文本。

1 个答案:

答案 0 :(得分:0)

您需要指定文件的绝对路径。新的PowerShell流程(将以管理员身份运行)不会与当前会话在同一工作目录中运行。

尝试:

$StartParams = @{
    FilePath = "powershell.exe"
    Credential   = Get-Credential
    Verb = "RunAs"
    ArgumentList = "-File `"c:\temp\Test.ps1`" -FilesPath `"S:\Files`" -CountryCode `"XXX`""
}
Start-Process @StartParams

如果您只知道相对路径,请使用Resolve-Path进行转换。例如:

ArgumentList = "-NoExit -File `"$(Resolve-Path test.ps1 | Select-Object -ExpandProperty Path)`" -FilesPath `"S:\Files`" -CountryCode `"XXX`""

您还应该查看字符串格式或here-string,这样您就可以避免转义每个双引号。它让你的生活更轻松:

#Using here-string (no need to escape double quotes)
ArgumentList = @"
-NoExit -File "$(Resolve-Path test.ps1 | Select-Object -ExpandProperty Path)" -FilesPath "S:\Files" -CountryCode "XXX"
"@

#Using string format
ArgumentList = '-NoExit -File "{0}" -FilesPath "{1}" -CountryCode "{2}"' -f (Resolve-Path test.ps1 | Select-Object -ExpandProperty Path), "S:\Files", "XXX"