xhr489
xhr489

Reputation: 2309

Create path from string in function in PowerShell

I want to pass a string to a path, it works if I don't have quotation marks around the path i.e. like:

C:\Users\David\Documents\Testing\$FolderName

But what if I want to have the quotation marks as bellow? Is there a way to avoid the error?

function CreateFolder {

 param([string]$FolderName)

 New-Item 'C:\Users\David\Documents\Testing\' + $FolderName -ItemType Directory
}


CreateFolder  'TestingSub'

I get this error:

New-Item : A positional parameter cannot be found that accepts argument '+'.

Upvotes: 0

Views: 214

Answers (1)

Paolo
Paolo

Reputation: 26034

You would need to evaluate the expression before New-Item is called:

function CreateFolder {

 param([string]$FolderName)
 New-Item ('C:\Users\David\Documents\Testing\' + $FolderName) -ItemType Directory
}

You could also use double quotes for expansion:

function CreateFolder {

 param([string]$FolderName)
 New-Item "C:\Users\David\Documents\Testing\$FolderName" -ItemType Directory
}

or you could use Join-Path:

function CreateFolder {

 param([string]$FolderName)
 New-Item (Join-Path -Path 'C:\Users\David\Documents\Testing\' -ChildPath $FolderName) -ItemType Directory
}

Upvotes: 2

Related Questions