Select attributes or parameter with variable in PowerShell

偶尔善良 提交于 2019-12-11 05:27:22

问题


Using this code I get the desired result:

Get-Service | select Name,Status

But the following code will not work, do you know why? I want the user to choose his own selection of attributes. I store the attributes in a variable like shown below. But it won't work:

$param = "Name,Status"
Get-Service | select $param

回答1:


You have to create an array of the properties you want to select:

$param = "Name","Status"
Get-Service | select $param

Or you can split the string yourself to create an array:

$param = "Name,Status"
Get-Service | select ($param -split ',')



回答2:


You could also create a hash table, like this:

$params = @{Property=@('Name','Status')}
Get-Service | Select @params

And even add some extra parameters, like this:

$params = @{
            Property=@('Name','Status');
            First=10;
            }
Get-Service | Select @params


来源:https://stackoverflow.com/questions/38891211/select-attributes-or-parameter-with-variable-in-powershell

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