Powershell复制文件或获取内容而不锁定它

时间:2016-01-06 07:15:42

标签: powershell

我们有一些预定的脚本。他们必须使用点源函数访问文件“Functions.ps1”。此“Functions.ps1”位于共享上。因为ExecutionPolicy我无法像这样加载文件:

. \\share\folder\Functions.ps1

预定脚本必须复制到本地C:\并加载文件:

$str_ScriptPath = "$($env:LOCALAPPDATA)\$(Get-Random -Minimum 0 -Maximum 100000)_Functions.ps1"
Copy-Item -Path "$str_Share\Functions.ps1" -Destination $str_ScriptPath -Force   
. $str_ScriptPath
Remove-Item -Path $str_ScriptPath 

问题是某些脚本是同时安排的 在这种情况下,它会发生错误:

The process cannot access the file 'C:\Windows\system32\config\systemprofile\AppData\Local\88658_Functions.ps1' because it is being used by another process. 
At line:46 char:14
+     Copy-Item <<<<  -Path "$str_Share\Functions.ps1" -Destination $str_ScriptPath -Force

我没有看到错误告诉本地文件被锁定的原因。它应该是一个唯一的文件名,并且该文件不存在。
我认为因为复制项源($ str_Share \ Functions.ps1)被锁定。
我的问题:
1)有更好的方法来处理这个问题吗? 2)或者是否有工作场所?
谢谢你的帮助 帕特里克

1 个答案:

答案 0 :(得分:3)

您应该能够使用[System.IO.File]::Open()获取文件的非独占只读句柄:

function Copy-ReadOnly
{
    param(
        [Parameter(Mandatory)]
        [string]$Path,
        [Parameter(Mandatory)]
        [string]$Destination
    )

    # Instantiate a buffer for the copy operation
    $Buffer = New-Object 'byte[]' 1024

    # Create a FileStream from the source path, make sure you open it in "Read" FileShare mode
    $SourceFile = [System.IO.File]::Open($Path,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::Read)
    # Create the new file
    $DestinationFile = [System.IO.File]::Open($Destination,[System.IO.FileMode]::CreateNew)

    try{
        # Copy the contents of the source file to the destination
        while(($readLength = $SourceFile.Read($Buffer,0,$Buffer.Length)) -gt 0)
        {
            $DestinationFile.Write($Buffer,0,$readLength)
        }
    }
    catch{
        throw $_
    }
    finally{
        $SourceFile.Close()
        $DestinationFile.Close()
    }
}