Start-Process passing a hashtable in the ArgumentList

醉酒当歌 提交于 2019-12-11 07:09:23

问题


Consider the following situation:

Content 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

Content of the 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

We can't seem to find a way to pass in the [HashTable] for the argument $CitrixFarm. How is it possible to add that argument. or pass it on to the script called by Start-Process with elevated permissions and in a new PowerShell session?

When omitting the parameter $CitrixFarm all is working fine. So the problem really is with passing the HashTable.


回答1:


You should pass the hashtable in PowerShell object notation, just as you would if running the script from a PowerShell window.

How you construct the string is up to you.

You could

  • use a string template
  • use a quick-and-dirty call "@$((ConvertTo-Json $CitrixFarm -Compress) -replace ':','=')"
  • use a function to convert the hashtable object.

Below is effectively what you are trying to achieve.

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

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

Source: A Better ToString() Method for Hash Tables



来源:https://stackoverflow.com/questions/50490459/start-process-passing-a-hashtable-in-the-argumentlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!