Question:
Is there a way to pass an object such as a hashtable to a powershell script file via command line?
This is my code:
1 2 3 4 |
Param( [hashtable]$lookupTable = @{} ) |
I tried this:
1 2 |
powershell.exe -NonInteractive -ExecutionPolicy ByPass -File D:\script.ps1 @{APIKey="Uz9tkNhB9KJJnOB-LUuVIA"} |
@{APIKey="Uz9tkNhB9KJJnOB-LUuVIA"}
being the hashtable parameter.
Error:
1 2 3 4 5 |
D:\script.ps1 : Cannot process argument transformation on parameter 'lookupTable'. Cannot convert the "@{APIKey=Uz9tkNhB9KJJnOB-LUuVIA}" value of type "System.String" to type "System.Collections.Hashtable". + CategoryInfo : InvalidData: (:) [script.ps1], ParentContainsErrorRecordException + FullyQualifiedErrorId : ParameterArgumentTransformationError,script.ps1 |
Based on the error, its interpreting the parameter as a string. I am also passing this parameter through teamcity, which only accepts parameters directly and passes it to a command line shown above.
Is there anything I can do to the parameter to tell powershell that it is an object of type hashtable?
PS.
The inputs allowed by teamcity are:
- Script File
- Script execution mode [“Put script into PowerShell stdin with “-Command -” arguments” and “Execute .ps1 script with “-File” argument”].
- Additional command line parameters.
- Script arguments (enabled if “Execute .ps1 with -File argument” is selected)
This is the format teamcity is using to execute the script in -Command mode:
1 2 |
powershell.exe -NonInteractive [commandline params] -ExecutionPolicy ByPass -Command - < [script file] |
hence:
1 2 |
powershell.exe -NonInteractive @{ APIKey = 'Uz9tkNhB9KJJnOB-LUuVIA'} -ExecutionPolicy ByPass -Command - < D:\BuildAgent-02\work\2204bf4ff5f01dd3\scripts\script.ps1 |
This is the format teamcity is using to execute the script in -File mode:
1 2 |
powershell.exe -NonInteractive [commandline params] -ExecutionPolicy ByPass -File [script file] [script arguments] |
hence when i use script params:
1 2 |
powershell.exe -NonInteractive -ExecutionPolicy ByPass -File D:\BuildAgent-02\work\2204bf4ff5f01dd3\scripts\script.ps1 @{ APIKey = 'Uz9tkNhB9KJJnOB-LUuVIA'} |
Is there anyway to work around this format that teamcity is using? For eg. under script arguments, could I do -Command there to serialize the params?
Answer:
One option might be to modify the script to take that argument as [string[]], giving it key-value pairs in the arguments and then turn that into a hash table using ConvertFrom-StringData in the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$script = { param ( [string[]]$lookuplist ) $lookupTable = ConvertFrom-StringData ($lookuplist | out-string) $lookupTable } &$script 'APIKey=Uz9tkNhB9KJJnOB-LUuVIA','APIKey2=Uz9tkNhB9KJJnOB-LUuVIA' Name Value ---- ----- APIKey Uz9tkNhB9KJJnOB-LUuVIA APIKey2 Uz9tkNhB9KJJnOB-LUuVIA |