lunchbeast
lunchbeast

Reputation: 17

Spaces in path are giving me an aneurysm

Running Window 7 64-bit with PowerShell 4.0. I'm having problems getting PowerShell's Test-Path and New-Item cmdlets to work for my path name, which has embedded spaces. I've run several Google searches which pointed to several similar StackOverflow entries, and most (like this one) refer to wrapping the path name in quotes - double quotes if the path includes variables to be interpreted, as mine does - which I've done. Doesn't seem like it should be that difficult, and I'm sure I'm overlooking something obvious, but nothing jumps out.

Here's the code fragment giving me grief - $mnemonic is part of a long parameter list that I shortened for brevity.

Param(
    [string]$mnemonic = 'JXW29'
)

$logdir = "T:\$$PowerShell Scripts\logs\STVXYZ\$mnemonic\"

if ((Test-Path "$logdir") -eq $false)
#if ((Test-Path 'T:\$$PowerShell Scripts\logs\STVXYZ\JXW29\') -eq $false)
    New-Item -Path "$logdir" -ItemType Directory
    #New-Item -Path 'T:\$$PowerShell Scripts\logs\STVXYZ\JXW29' -ItemType Directory

Even though the last node in the directory does not exist, the Test-Path check returns true and my code blows right past the New-Item that should have created it. There are statements further down in the rest of the script that write to that directory that do not fail - no idea where they're really writing to.

If I uncomment and run the commented code, which which uses a literal string for the path instead of one with variables, everything works. First time through, the STVXYZ folder is not found and is created. Second time through, it's detected and the New-Item is skipped.

Upvotes: 0

Views: 131

Answers (2)

ahhbeemo
ahhbeemo

Reputation: 21

It is unclear what you are trying to do with "$$PowerShell Scripts". Is that also a variable ?

$$ contains the last token of last line input into the shell

I am assuming you should just take that out. A good way to test what you are actually testing is to just Write-Host $logdir prior to testing

param ( 
[string] $mnemonic = 'JXW29' 
)

$logdir = "T:\PowerShell Scripts\logs\STVXYZ\$mnemonic\"

Write-Host "path I am testing: $logdir"

if ($(Test-Path $logdir) -eq $False){
    mkdir $logdir
}

Upvotes: 2

lunchbeast
lunchbeast

Reputation: 17

Never mind, found it. Those extra $$'s that are in my path name needed to be escaped.

Upvotes: 0

Related Questions