Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append string literals to properties returned from a Select-Object command

Tags:

powershell

How do you concatenate a string literal and parameter in a Select-Object.

For Example I have:

Get-AdUser -filter * | Select-Object 'sip'+SamAccountName,Name, Email, etc

Basically I want to return the property SamAccountName from the AdUser with the string literal sip before it.

I tried everything I can think of.

Thanks!

Edit: added parameters and multiple users

like image 971
Eitan Avatar asked Oct 02 '13 19:10

Eitan


People also ask

How do I append to a string in PowerShell?

In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator.

How do I convert an object to a string in PowerShell?

The Out-String cmdlet converts input objects into strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the Stream parameter to direct Out-String to return one line at a time or create an array of strings.

How do I add a property to a PowerShell object?

The Add-Member cmdlet lets you add members (properties and methods) to an instance of a PowerShell object. For instance, you can add a NoteProperty member that contains a description of the object or a ScriptMethod member that runs a script to change the object.

How do you select an object property?

To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters. To select object properties, use the Property parameter. When you select properties, Select-Object returns new objects that have only the specified properties.


2 Answers

You can specify an expression in a script block to do this. Like this:

 Get-AdUser [email protected] | select-object {"sip"+$_.SamAccountName}

Though if you do it this way, the name of resultant property looks a bit weird. To specify the property name as well, enclose the script block as part of a hashtable that specifies the name of the new property as well as the scriptblock expression to generate it. It would look like this:

Get-AdUser [email protected] | select-object @{name="SamAccountName"; expression={"sip"+$_.SamAccountName}}
like image 195
zdan Avatar answered Oct 21 '22 10:10

zdan


You don't need to use Select-Object, because you're not trying to create a new object with specific properties; you're trying to select a single property (SamAccountName) and manipulate it.

"sip" + (Get-ADUser [email protected]).SamAccountName
like image 21
Adam Maras Avatar answered Oct 21 '22 12:10

Adam Maras