Creating New Directory as Different User

I am creating a script to:

  1. Create a directory in Program Files
  2. Copy a XML file from TFTP server to the newly created directory
  3. Run the XML
We have removed administrative rights from all users from the domain. When attempting to create a folder in the local Program Files (I am running as a test user without admin rights but supply admin rights credentials at prompt), I get an error:
md "\Program Files\Test" -Credential Get-Credential
md : The FileSystem provider supports credentials only on the New-PSDrive cmdlet. Perform the operation again without
specifying credentials.
My Full Script:
$host.UI.RawUI.WindowTitle = "XMLTestFile1"
$sourcePath = "\\TFTPServer\Folderlocation\Filename.xml"
$destPath = "\Program Files\TestFile1"
$File = "\Program Files\Test\Filename.xml"

Write-Host “Local File NOT Found … Copying Files & Starting Filename.xml”
$UserName = Read-Host ‘Please enter your AD Username’
md -Path “\Program Files\Test” -Credential (Get-Credential -Username “$ENV:UserDomain$UserName” -Message ‘Enter your password’)
Start-BitsTransfer -Source $sourcePath -Destination $destPath
Start-Process $File -ErrorAction Stop
break
}
catch {
Write-Output “Missing/Invalid Credentials”
Write-Output “Please ensure you AD account is not locked”
Write-Host “”;
Write-Output “Enter Credentials again? [Y/N]”
if ((Read-Host) -ne “Y”) { break }

}
}


Any help is appreciated!

You shouldn’t need to specify credentials for the local user to create the directory. Have you tried the command without specifying the credential parameter (defaults to current user)?

New-Item -Path $env:ProgramFiles -Name Test -ItemType Directory

Program Files requires administrative rights to write to that directory. Have you adjusted the permissions of the Program Files folder?

If the user is running the script, it should be running as them already and therefore you wouldn’t need to provide credentials.