【问题标题】:Powershell copy item into shared drive with username and passwordPowershell 使用用户名和密码将项目复制到共享驱动器
【发布时间】:2020-02-17 07:43:33
【问题描述】:

我正在使用 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()
}
}

我收到错误“拒绝访问”。 如果有人可以帮助我在代码中包含用户名和密码,我将不胜感激。

【问题讨论】:

  • 为什么要把Test-FileLock函数放在try块里面? Copy-Item 也有一个 Credentials 参数。
  • "我不介意在代码中包含用户名和密码,因为对用户没有任何限制。"在代码中硬编码凭据通常不是一个好习惯。由于您已在此脚本中硬编码 $destfolder,您可能会考虑将脚本作为 Windows 任务运行,并在保存任务时将写入所需的凭据传递给 $destfolder。此凭据(用户名)将显示为任务的“作者”。

标签: powershell


【解决方案1】:

将此参数添加到您的Test-FileLock 函数中。

param (
    [ValidateNotNull()]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $Credential = [System.Management.Automation.PSCredential]::Empty
)

这将创建一个安全的凭据对象,您可以在其中存储您的凭据,而无需将它们硬编码到您的脚本中。另请参阅此链接How to Add Credentials To PowerShell。

你应该尝试使用

Copy-Item -Path $path -Destination $destfolder -Credentials $Credential -Force -Verbose -PassThru

如果这不起作用,请添加您的完整错误消息并告诉我们哪个命令破坏了您的代码。

编辑

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

  1. 从 PSGallery 安装和导入 Credential Manager
Install-Module CredentialManager
Import-Module CredentialManager
  1. 使用New-StoredCredential 创建一个新帐户
$cred = New-StoredCredential -UserName TestAccount -Password P@ssw0rd
  1. 您可以使用
  2. 检索凭据
Get-StoredCredentials | where { $_.UserName -eq TestAccount }

此对象现在是安全字符串类型。此命令和下一个命令(第 4 步)应在您的脚本中,以检索凭据并将其转换为 PSCredential 对象。

  1. 要创建 PSCredential 对象,请输入:
$credentials = New-Object -TypeName System.Management.Automation.PSCredential($cred.UserName, $cred.Password)

现在你得到了一个 PSCredential 对象,你应该可以将它用作 Copy-Item 的脚本。

【讨论】:

  • 请原谅我的问题,我是初学者。添加上述内容后,我现在被提示输入用户名和密码。这不起作用,因为我的脚本正在监视文件夹并且可以随时运行。请指教
  • @EyadAlkhatib,我更新了答案。尝试将凭据存储在您的管理器中,并在脚本运行时检索它们。
  • 我已经添加了您提供的 5 行,然后我在 copy-item 语句中调用了 $credentials,但我收到了这个错误:New-StoredCredential : The term 'New-StoredCredential'不被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,如果包含路径,请验证路径是否正确并重试
  • 该错误意味着该模块可能没有为您的脚本导入。在调用 New-StoredCredential 之前导入 CredentialManager 模块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
  • 2011-04-11
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
相关资源
最近更新 更多