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

标签 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)还是有工作环境?

感谢帮助
帕特里克

最佳答案

您应该能够使用[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()
    }
}

关于powershell - Powershell复制文件或获取内容而不锁定它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34627593/

相关文章:

windows - 从 Windows 中的\文件夹中删除非 native 计划任务

function - 调用函数时出错

powershell - 单选按钮 - Powershell

powershell - 获取控制台模式时发生 Win32 内部错误 "The handle is invalid"0x6

从 R : Unexpected token in expression or statement 运行 powershell 命令

powershell - 在 Powershell 中压缩文件夹时捕获错误

powershell - 如何将 powershell out-string 中的字符串作为参数传递给 get-content/cat (直接)?

c# - 使用 powershell 批处理文件运行 c# exe

function - 是否可以在PowerShell中同时运行2个功能?

PowerShell:限制变量值