我遇到了一些我不明白的奇怪事情。我的场景:
我有C:Functions
多个 .ps1 文件。我想将文件的内容复制到一个文件(AllFunctions.ps1
)。文件CopyFunctions2AllFunctions.ps1
是执行我的命令的文件。
$path="C:Functions*.ps1"
$destination="C:FunctionsAllFunctions.ps1"
Clear-Content -Path C:FunctionsAllFunctions.ps1
Get-Content -Path $path -Exclude "C:FunctionsCopyFunctions2AllFunctions.ps1" | Add-Content -Path $destination
错误消息是德语,但是,它说无法访问AllFunctions.ps1,因为它用于另一个进程。
如果替换,代码有效
$path="C:Functions*.ps1"
具有特定的文件名,例如
$path="C:FunctionsRead-Date.ps1"
-Force
没有帮助
此外,代码一直工作到Add-Content -Path $destination
.当我执行Get-Content...
时,终端不仅向我显示 .ps1 文件中的内容,还显示终端的内容,以及我在尝试时遇到的所有错误......
有人有想法吗?
此代码中有 2 件事需要修复,首先是新代码:
$path="C:Functions"
$destination="C:FunctionsAllFunctions.ps1"
Clear-Content -Path C:FunctionsAllFunctions.ps1
$functions=Get-ChildItem -Path $path -Exclude CopyFunctions2Profile.ps1 | Get-Content
Add-Content -Path $destination -Value $functions
问题 #1
$path="C:Functions*.ps1"
不行,PS也在复制终端的内容,不知道为什么...因此,我们不会在$path中使用通配符。
因此,我们需要在代码中使用Get-Childitem
如下所示:
$functions=Get-ChildItem -Path $path -Exclude CopyFunctions2Profile.ps1 | Get-Content
问题 #2
使用管道时,PS 处理一个项目并通过管道发送它,然后是第二个项目,依此类推。因此,当项目 2 发送到Add-Content
时,"AllFunctions.ps1"仍用于项目 1。
因此,我们需要将Get-Content
保存在变量($functions)
中,然后在Add-Content
中使用它。