Home > Mobile >  Powershell $PSSscript root - how to add "\" to directory
Powershell $PSSscript root - how to add "\" to directory

Time:07-31

I've ran into a problem in my powershell code:

I would like to take $PSScriptRoot.ToString(); and then add it \childfoldername so it should look like this

$PSScriptRoot = C:\New Folder\childfoldername

assuming that is $PSScriptRoot = C:\New Folder.

Tried $PSScriptRoot.ToString() "\" foldername but with no luck, still getting an error:

A positional parameter cannot be found that accepts argument ' '.

CodePudding user response:

You can use the Join-Path function.

$newPath = Join-Path -Path $PSScriptRoot -ChildPath "childpath"

CodePudding user response:

A positional parameter cannot be found that accepts argument ' '.

This error message implies that your problem isn't your expression per se ($PSScriptRoot.ToString() "\" foldername) but your attempt to pass it as an argument to a command, without enclosing it in (...).

# !! WRONG - attempt to pass an expression as an argument as-is.
Get-Content $PSScriptRoot.ToString()   "\"   'foldername'
# OK - enclosing the expression in (...) works as intended.
Get-Content ($PSScriptRoot.ToString()   "\"   'foldername')

Aside from that, as noted:

  • You don't need to call .ToString() on the automatic $PSScriptRoot variable, because it already is a string.

  • The preferable way to synthesize a path is to use the Join-Path cmdlet:

    Get-Content (Join-Path $PSScriptRoot 'foldername')
    
  • Related