【问题标题】:New-Item: Access Denied新项目:拒绝访问
【发布时间】:2017-11-07 22:30:20
【问题描述】:

我对 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 并让它创建目录。相反,我收到一个错误,将在下面列出。如果我尝试在不指定凭据的情况下运行此脚本,则会列出第二个错误。

第一个错误:

文件系统提供程序仅支持 New-PSDrive 上的凭据 cmdlet。在不指定凭据的情况下再次执行该操作。

第二个错误:

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

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

【问题讨论】:

  • 您当前的用户帐户是否有权更改该目的地?如果是,则无需指定-Credential
  • 如果您的帐户无权访问该位置,我建议您也将-Credential $cred 传递给Test-Path,否则会因访问被拒绝而出错。
  • @iRon env: 是驱动器,是的,但从该驱动器调用变量只是一个字符串。 $env:HomeDrive.GetType() => System.String

标签: powershell credentials


【解决方案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 }

这是等待文件夹存在。

【讨论】:

    【解决方案2】:

    如果您的用户帐户有权访问指定的位置,则无需指定凭据。但是,如果是,您还应该将凭据传递给 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'
    

    【讨论】:

    • Test-Path -Path $Path -Credential $Credential 返回关于文件系统提供程序的第一个错误
    • @Jelphy 假设默认值,$env:HOMEDRIVE 解析为 C:D: 文字字符串。如果他正在编写脚本,他应该明确定义参数,这样就不会发生这样的神秘消息。如果这些不是映射驱动器,那就太奇怪了。
    猜你喜欢
    • 2018-07-02
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多