PS New-Item : Access is denied runs fine from comm

2019-08-31 09:17发布

问题:

I'm trying to create a script that's triggered by a TFS build that creates a new directory on a network share and then saves the location of that share in an environment variable.

Here's the (abridged) script as it originally was:

$NewPathForFiles = "\\NetworkShareName \" + "ProductName "+ $MajorBuildNumber 

New-Item -Path $NewPathForFiles -ItemType directory # Create the folder

But when I run the the script from TFS I get this error:

New-Item : Access is denied

I can run the script from the command prompt even logged in as the service account running TFS build, but from within the build I get the error.

I fixed this by mapping a drive to the share using -Credential, but that means I need to hard-code the password for the ID in the script which I'd prefer not to do:

$pass = ConvertTo-SecureString "MyPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("MyID",$pass)

New-PSDrive -Name P -PSProvider FileSystem -Root "\\MyNetworkShare" -Credential $cred

$NewPathForFiles = "p:\ProdctName " + $MajorBuildNumber 

New-Item -Path $NewPathForFiles -ItemType directory # Create the folder

Anyone have any ideas how I can do this without having to hard-code the PW?

回答1:

Thanks to @TheIncorrigible1 for the answer. Adding the -Force to the New-Item fixed the issue. Thanks!