gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:12:13 24 4
gpt4 key购买 nike

我们有一些预定的脚本。他们必须访问带有点源函数的文件“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com