【发布时间】: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