代码之家  ›  专栏  ›  技术社区  ›  DarkLite1

在提升模式下使用多个命名参数调用脚本

  •  0
  • DarkLite1  · 技术社区  · 7 年前

    测验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 回复  |  直到 7 年前
        1
  •  0
  •   Frode F.    7 年前

    您需要指定文件的绝对路径。新的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`""
    

    您还应该查看字符串格式或此处的字符串,以便避免转义每个双引号。它让您的生活更轻松:

    #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"