Creating new directory via powershell

grahamco
grahamco used Ask the Experts™
on
I am performing several copy and move tasks via a PS script which calls upon the "%appdata% user environment variable. I've run into an issue with one line of the script which creates a new folder, the issue is the folder is created in the directory that the script is executed from causing the next action which moves files to the new folder to fail.

Here is the line causing the issue: New-Item -Path "%APPDATA%\Microsoft\Templates\" -Name "TGCTemplates" -ItemType "directory"

Is there another cmdlet to create the new directory that ensures its created in the user profile?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Like this; use the "env" drive; PowerShell doesn't use the percent signs:
New-Item -Path "${env:APPDATA}\Microsoft\Templates\" -Name "TGCTemplates" -ItemType "directory"

Open in new window

Top Expert 2014

Commented:
Just to describe the issue, PowerShell has no idea about variables in this notation ( %something% ).  That is a syntax when working in the cmd shell (and other programs which have been designed to be aware of it).  PowerShell exposes environment variables through the $env variable and the env: drive (can also be accessed via .Net classes).
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Oh, and fun fact: if you have a string that might (or not) contain an environment variable (so you can't really use a static variable name), you can expand said string using the ExpandEnvironmentVariables() method:
$path = "%APPDATA%\Microsoft\Templates\"
[Environment]::ExpandEnvironmentVariables($path)

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial