Bilal Habib
Bilal Habib

Reputation: 97

I need help combining a string and a variable

Hi i am working on using New-Item with the option -Path, in the path I want the string of the path and then a variable that the end of that path

I have tried "\\path\S_."Variable""

This is what I have so far

New-Item -Path "\\servername\Share" -Name $_."samAccountName" -ItemType "directory" -Force

what i want is the variable to be included in the path after share.

What I tried above has not worked so far

Upvotes: 0

Views: 50

Answers (3)

Theo
Theo

Reputation: 61013

The safest way to create paths is by using the Join-Path cmdlet.

$newFolder = Join-Path -Path '\\Servername\Share' -ChildPath ($_.SamAccountName)
New-Item -Path $newFolder -ItemType Directory -Force | Out-Null

Note: I ended the command with | Out-Null to avoid console output

Upvotes: 2

T-Me
T-Me

Reputation: 1884

To use dot-noted Variables in parameters use them in brackets (the samAccountName too):

New-Item -Path "\\servername\Share_$($_.variable)" -Name ($_.samAccountName) -ItemType "directory" -Force

another way is to build your string with the format operator -f:

New-Item -Path ("\\servername\Share{0}" -f ($_.var) ) -Name ($_."samAccountName") -ItemType "directory" -Force

{0} is replaced by the expression at position 0 behind the -f so you could build a string with multiple expressions>

"{0} , {1} , {2}" -f ($_.var),($var + 3),(get-date)

Upvotes: 2

Mark Harwood
Mark Harwood

Reputation: 2405

To to this, it's as simple as:

"\\servername\$variable"

or

$variable = "\\servername\" + $variable

Upvotes: 0

Related Questions