Start-Process在ArgumentList

时间:2018-05-23 14:04:14

标签: powershell arguments parameter-passing start-process

考虑以下情况:

内容MyScript.ps1

Param (
    [String]$CountryCode,
    [String]$FilesPath,
    [String]$KeepassDatabase,
    [String]$KeepassKeyFile,
    [String]$EventLog = 'HCScripts',
    [String]$EventSource,
    [HashTable]$CitrixFarm = @{'Server1' = '6.5'}
)

$CountryCode
$FilesPath
$KeepassDatabase
$KeepassKeyFile
$EventLog
$EventSource
$CitrixFarm

Caller.ps1的内容:

Param (
    $FilesPath = ".\MyScript.ps1",
    $EvenntLog = 'Test',
    $CountryCode = 'BNL',
    $KeepasDatabase,
    $KeepasKeyFile
)

$Arguments = @()
$Arguments += "-EventSource ""$AppName"""
$Arguments += "-EventLog ""$EventLog"""
$Arguments += "-FilesPath ""$((Get-Item $FilesPath).FullName)"""
$Arguments += "-CountryCode ""$CountryCode"""
$Arguments += "-KeepassDatabase ""$((Get-Item $KeepasDatabase).FullName)"""
$Arguments += "-KeepassKeyFile ""$((Get-Item $KeepasKeyFile).FullName)"""
$Arguments += "-CitrixFarm $CitrixFarm"

$StartParams = @{
    Credential   = $Credentials
    ArgumentList = "-File ""$ScriptPath"" -verb runas" + $Arguments
    WindowStyle  = 'Hidden'
}
Start-Process powershell @StartParams

我们似乎找不到传递参数[HashTable] $CitrixFarm的方法。如何添加该参数是可能的。或者使用提升的权限和新的PowerShell会话将其传递给Start-Process调用的脚本?

省略参数$CitrixFarm时,一切正常。所以问题在于传递HashTable

1 个答案:

答案 0 :(得分:1)

您应该以PowerShell对象表示法传递哈希表,就像从PowerShell窗口运行脚本一样。

你如何构建字符串取决于你。

你可以

  • 使用字符串模板
  • 使用快速拨打电话"@$((ConvertTo-Json $CitrixFarm -Compress) -replace ':','=')"
  • use a function转换哈希表对象。

以下是您要实现的目标。

$Arguments = @()
...
$Arguments += "-CitrixFarm @{'Server1' = '6.5'}"

$StartParams = @{
    Credential   = $Credentials
    ArgumentList = "-File ""$ScriptPath"" -verb runas" + $Arguments
    WindowStyle  = 'Hidden'
}
Start-Process powershell @StartParams

来源:A Better ToString() Method for Hash Tables