新项目:访问被拒绝

时间:2017-11-07 13:56:40

标签: powershell credentials

我仍然是Powershell的新手,我认为这将是一件容易的事。对于我的工作,我需要一遍又一遍地创建一组文件夹,此时我已经厌倦了用鼠标执行此操作,因为我可以自动执行任务并继续处理更紧迫的问题。以下是我尝试做的一个示例。

$cred = Get-Credential

$Test1 = Test-Path "$env:HOMEDRIVE\Inetpub\wwwroot\MAKEthisFOLDER"

if ($test1 -eq $false) {
    new-item "$env:HOMEDRIVE\Inetpub\wwwroot\MAKEthisFOLDER" -ItemType Directory -Credential $cred
}

else {
    Write-Host "Folder already exists" -ForegroundColor Yellow -BackgroundColor red 
}

我想我可以将我的凭据传递给new-item并让它创建目录。相反,我收到一个错误,将在下面列出。如果我尝试在不指定凭据的情况下运行此脚本,那么我会列出第二个错误。

第一个错误:

  

FileSystem提供程序仅支持New-PSDrive上的凭据   小命令。无需指定凭据即可再次执行操作。

第二个错误:

  

新项目:访问路径' MAKEthisFOLDER'被拒绝。

我知道这非常简单,但任何想法都会非常感激。

2 个答案:

答案 0 :(得分:1)

尝试使用New-PSDrive并为其分配凭据,如:

$cred = Get-Credential
$Test1 = Test-Path "$env:HOMEDRIVE\Inetpub\wwwroot\MAKEthisFOLDER"

if ($test1 -eq $false) {
    $homedrive = $env:HOMEDRIVE
    New-PSDrive -Name $homedrive -PSProvider FileSystem -Root "\\Inetpub\wwwroot\MAKEthisFOLDER" -Credential $cred
    new-item "$env:HOMEDRIVE\Inetpub\wwwroot\MAKEthisFOLDER" -ItemType Directory
}
else {
Write-Host "Folder already exists" -ForegroundColor Yellow -BackgroundColor red }

这是待处理的文件夹。

答案 1 :(得分:0)

如果您的用户帐户有权访问指定的位置,则无需指定凭据。但是,如果是,您还应该将凭证传递给Test-Path以获得有效的回复。

$Credential = Get-Credential
$Path = "$env:HOMEDRIVE\Inetpub\wwwroot\MAKEthisFOLDER"

If (-not (Test-Path -Path $Path -Credential $Credential -PathType 'Container'))
{
    ## -Force creates the folder structure if it doesn't exist
    New-Item -Path $Path -ItemType 'Directory' -Credential $Credential -Force
}
Else
{
    Write-Host "'$Path' already exists" -ForegroundColor 'Yellow' -BackgroundColor 'Red'
}

另一种选择(无论其他因素如何都应该有效)

New-PSDrive -Name 'INET' -PSProvider 'FileSystem' -Root "$env:HomeDrive\Inetpub\wwwroot" -Credential (Get-Credential)
If (-not (Test-Path -Path 'INET:\MAKEthisFOLDER'))
{
    New-Item -Path 'INET:\MAKEthisFOLDER' -ItemType 'Directory'
}
Else
{
    Write-Host "Folder already exists" -ForegroundColor 'Yellow' -BackgroundColor 'Red'
}
Remove-PSDrive -Name 'INET'