A
A
Alexey2016-09-08 12:19:37
PowerShell
Alexey, 2016-09-08 12:19:37

Passing parameter names through variables in PowerShell?

PowerShell has Set constructs, such as

Set-Content -Path 'C:\Logs\1.txt' -Value 'Текст для вывода'

This command will output the values ​​to the file 'C:\Logs\1.txt'.
There are commands that can take the name of a parameter through an array with keys
-prelace @{Ключ=Значение}
-clear @{Ключ=Значение}

Everything is fine with them, they chew variables and instead of a value and instead of a key.
-prelace @{$Key=$Value}
-clear @{$Key=$Value}

For example if you do this
$Value= '-Value'
$Value.GetType().FullName - так мы узнаем что это System.String[]
Set-Content -Path 'C:\Logs\1.txt' $Value 'Текст для вывода'
Получим ошибку, нет параметра для приема значения 'Текст для вывода'

Actually the question is how it is possible to pass through a variable not only the value but also the key/parameter (-Path, -Value) to the command/function. Let me explain what the catch is, one value can correspond to two different keys, one for calling in a function, the second for passing through an array. In general, the crutch through the array works, but you always want something more.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
azarij, 2016-09-09
@skazi_premiere

$parms = @{'class'='Win32_BIOS';
'computername'='SERVER-R2';
'filter'='drivetype=3';
'credential'='Administrator'
}
Get-WmiObject @parms
something like this.
$parms.computername = "whatever" - if you need to change the parameter value on the fly.

A
Alexander, 2016-11-15
@asand3r

Is splatting wrong?
https://technet.microsoft.com/en-us/library/gg6759...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question