PowerShell Access Network Share In Script As Different User

Viewed 2027

I am trying to access a domain network share in my PowerShell script that is currently running as NETWORK SERVICE. I have a domain user credential configured below.

$secStringPassword = ConvertTo-SecureString "password" -AsPlainText -Force
$shareCredential = New-Object System.Management.Automation.PSCredential ("DOMAIN\Username", $secStringPassword)

I would like to be able to run the following commands in the PowerShell script as the user specified above.

New-Item -Path "\\SERVER\Share\Folder" -ItemType Directory
Get-ChildItem "\\SERVER\Share\Folder"

Running the below is showing as not supported:

New-Item -Path "\\SERVER\Share\Folder" -ItemType Directory -Credential $shareCredential 
1 Answers

"The New-Item cmdlet creates a new item and sets its value" If you're trying to connect to a share as a different user I suggest using new-psdrive first to create a mount as that user. This mounts that share as a drive so that it behaves more like a local location than a UNC path

New-PSDrive -Name "ShareNAME" -PSProvider "FileSystem" -Root "\\Server\Share" -Credential $shareCredential
New-Item -Path ShareNAME:\Folder -ItemType Directory -Credential $shareCredential
Get-ChildItem ShareNAME:\Folder -Credential $shareCredential
Related