Powershell使用用户名和密码将项目复制到共享驱动器

Powershell使用用户名和密码将项目复制到共享驱动器,powershell,Powershell,我正在使用powershell脚本将文件从本地计算机复制到网络共享文件夹 当共享文件夹不需要身份验证时,代码工作正常,没有问题。我不介意在代码中包含用户名和密码,因为对用户没有任何限制 $folder = 'D:\test' $destfolder='\\192.168.2.76\ENT' $filter = '*.AVI' $fsw = New-Object System.IO.FileSystemWatcher $folder,

我正在使用powershell脚本将文件从本地计算机复制到网络共享文件夹


当共享文件夹不需要身份验证时,代码工作正常,没有问题。我不介意在代码中包含用户名和密码,因为对用户没有任何限制

$folder = 'D:\test'

$destfolder='\\192.168.2.76\ENT'
$filter = '*.AVI'                             

$fsw = New-Object System.IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $true              
NotifyFilter          = [System.IO.NotifyFilters]'FileName, LastWrite'
}

$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {



[int]$sleepTime = 500
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated


try {
    # **********check if the file is locked by another process (still being received from the soource)********
    function Test-FileLock {
        param (
            [parameter(Mandatory = $true)][string]$Path
        )

        $oFile = New-Object System.IO.FileInfo $Path

        if ((Test-Path -Path $Path) -eq $false) {
            return $false
        }

        try {
            $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)

            if ($oStream) {
                $oStream.Close()
            }
            $false
        }
        catch {
            # file is locked by another process.

            return $true
        }
    }
    #******** End of Function (test if file is locked) *****************
    # below line : will keep testing if the file is locked ************
    while (Test-FileLock $path) { Start-Sleep 10 }

    # below line: once the file becomes "NOT Locked" , copy the file to the destination folder *******
    Copy-Item  $path  $destfolder -Force -Verbose -PassThru 
}
catch {
    $error|Out-File  -FilePath d:\outlog.txt -Append
    $Error.Clear()
}
}
我收到错误“拒绝访问”。
如果有人能帮助我在代码中包含用户名和密码,我将不胜感激。

将此参数添加到您的
测试文件锁定功能中

param (
    [ValidateNotNull()]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $Credential = [System.Management.Automation.PSCredential]::Empty
)
这将创建一个安全的凭证对象,您可以在其中存储凭证,而无需将其硬编码到脚本中。另请参见此链接

然后,您应该尝试使用

Copy-Item -Path $path -Destination $destfolder -Credentials $Credential -Force -Verbose -PassThru
如果这不起作用,请添加完整的错误消息,并告诉我们哪个命令会破坏您的代码

编辑

您还可以在计算机上存储凭据,然后从凭据管理器中检索凭据

  • 从PSGallery安装并导入凭据管理器
  • 使用
    newstoredcredential
  • 您可以使用检索凭据
  • 此对象现在是安全字符串类型。此命令和下一步(步骤4)应在脚本中,以检索凭据并将其转换为PSCredential对象

  • 要创建PSCredential对象,请输入:

  • 现在您得到了一个PSCredential对象,您应该能够将它作为脚本用于复制项。

    为什么要将函数测试文件锁放在try块中
    Copy Item
    还有一个
    Credentials
    参数。“我不介意在代码中包含用户名和密码,因为对用户没有限制。”在代码中硬编码凭据通常不是一个好做法。在这个脚本中,您已经硬编码了<代码> $DestFasks/COD>,您可以考虑将脚本运行为Windows任务,并在保存任务时将所需的凭据传递给<代码> $DestFalths。此凭据(用户名)将显示为任务的“作者”。请原谅我的问题,我是初学者。在添加了以上内容之后,我现在被提示输入用户和密码。这将不起作用,因为我的脚本正在监视文件夹,可以随时运行。劝告please@EyadAlkhatib,我更新了答案。尝试将凭据存储在您的管理器中,并在脚本运行时检索它们。我已添加了您提供的5行,然后在copy item语句中调用了
    $credentials
    ,但出现以下错误:New StoredCredential:术语“New StoredCredential”无法识别为cmdlet、函数、脚本文件的名称,或可操作程序。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试该错误表示可能没有为脚本导入模块。调用
    newstoredcredential
    之前,请导入CredentialManager模块。
    Install-Module CredentialManager
    Import-Module CredentialManager
    
    $cred = New-StoredCredential -UserName TestAccount -Password P@ssw0rd
    
    Get-StoredCredentials | where { $_.UserName -eq TestAccount }
    
    $credentials = New-Object -TypeName System.Management.Automation.PSCredential($cred.UserName, $cred.Password)