在 Windows 10 上使用 PowerShell 5.1,我成功映射了驱动器,但通过计划任务运行时却没有成功映射驱动器

问题描述 投票:0回答:1

以下代码在 Windows 10 和 11 上成功创建映射驱动器。从任务计划程序运行脚本不起作用。该任务已配置为作为系统运行,我也尝试使用相同的管理员帐户登录。任务已配置Windows 7和2008 R2,我已经针对Windows 10进行了测试。任务中的操作是PowerShell.exe -executionpolicy 绕过 -file .ps1.

感谢任何可以提供帮助的人。 阿莫斯

$networkSharePath = "\\iilansweepcl1\defaultpackageShare$\Post-Install\Patches"
$localPath = "C:\Windows\Patches\"
$publicDesktopPath = [Environment]::GetFolderPath("CommonDesktopDirectory")
$global:driveLetter = "f:"

If (-not (Test-Path -Path "${localPath}exclutions.txt"))
{
    New-Item -Path "${localPath}exclutions.txt"
}

$FilesOnShare = @{ }
$FilesLocal = @{ }

function decode_password()
{
    param (
        $enc_pass
    )
    return [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($enc_pass))
}

function Connect2PackageShare
{
    $UserName = "******admin"
    $password = ConvertTo-SecureString  "$(decode_password 'aW**********y')" -AsPlainText -Force
    $credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password

    try
    {
        net use $driveLetter $networkSharePath /user:*****admin ilishelpYOU2 /persistent:no | Out-Null  
        #New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root $networkSharePath -Scope Global -ErrorAction stop
    }
    catch
    {
        Try
        {
            net use $driveLetter $networkSharePath /user:*****admin ilishelpYOU2 /persistent:no | Out-Null
            #New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root $networkSharePath -Credential $credential -Scope Global -ErrorAction Stop
        }
        catch
        {
            exit
        }
    }
    
    $Files = Get-ChildItem -Path 'B:\'
    foreach ($File in $Files)
    {
        $LastWriteTime = $File.LastWriteTime
        $FilesOnShare[$File.Name] = $LastWriteTime
    }
    Return $FilesOnShare
} # Connect2PackageShare

function Get-LocalPostInstall
{
    $result =  Get-Item -Path $localPath
    if ($result)
    {
        $LFiles = Get-ChildItem -Path $localPath
        foreach ($Lfile in $Lfiles)
        {
            $LastWriteTime = $Lfile.LastWriteTime
            $FilesLocal[$Lfile.Name] = $LastWriteTime
        }
    }
    Return $FilesLocal
} # Get-LocalPostInstall

Connect2PackageShare
powershell scheduled-tasks mapped-drive
1个回答
0
投票
  • 映射驱动器是一个用户级概念,因此您必须从根本上在应该看到它们的帐户上下文中建立它们。

  • 在计划任务的上下文中,您必须进一步确保任务具有网络访问权限,如果您以SYSTEM身份运行,或者即使您使用特定目标用户身份运行但具有选择了

    Run whether user is logged on or not
    选项。
    
    

  • 因此,要使您的脚本正常工作:

    将您的任务配置为运行
  • 作为应为其建立映射的用户或用户组

    例如,使用
      Users
    • 组为所有用户建立驱动器。
      
      
  • 使用
  • Run only when the user is logged on

    选项。

    
    

    请注意,这意味着任务始终以“可见”方式运行。但是,如果您安排它在登录时运行,这可能不是问题。
    • 请勿使用 Run with highest privileges
    • 选项(默认情况下,给定用户的提升进程不会与非提升进程共享驱动器映射,并且从提升进程建立的映射不会持久)。
  • 
    
© www.soinside.com 2019 - 2024. All rights reserved.