我在 GitHub 的一個變數中有內容,我想匯出然后到我的本地機器上自動創建的檔案
我試過用
$FileContent | Out-File ('C:\Devjobs\clonefolder' '\' $repo.name '\' $srccontent.name)
它給出了錯誤
Out-File : Could not find a part of the path 'C:\Devjobs\clonefolder\bct-common-devcomm-codegen-messages\BCT.Common.DevComm.CodeGen.Messages.sln'.
At line:1 char:18
... lnContent | Out-File ('C:\Devjobs\clonefolder' '\' $repo.name ' ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException
FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
uj5u.com熱心網友回復:
正如stackprotector已經評論的那樣,錯誤顯示DirectoryNotFoundException,這意味著您正在嘗試在尚不存在的目錄中創建檔案。
為避免這種情況,首先創建輸出檔案的路徑,然后創建檔案。
$pathOut = Join-Path -Path 'C:\Devjobs\clonefolder' -ChildPath $repo.name
# create the folder path if it does not exist already
$null = New-Item -Path $pathOut -ItemType Directory -Force
# now write the file
$FileContent | Set-Content -Path (Join-Path -Path $pathOut -ChildPath $srccontent.name)
通過使用打開的-Force開關,New-Item您將創建目錄,或者如果檔案夾已經存在,則回傳一個 DirectoryInfo 物件。
在這種情況下,我們不再需要該物件,因此我們將其丟棄$null =。
請注意,這僅適用于檔案系統,如果您對注冊表項執行相同操作,您將丟失現有密鑰的所有內容!
注意:我使用Set-Content而不是Out-File因為在 PowerShell 版本(包括 5.1 及以下)上,Out-File不使用該-Encoding引數將以Unicode (UTF16-LE) 編碼寫入檔案,這可能是也可能不是您所期望的。
根據您的評論:
foreach ($srccontent in $srccontents) {
if (<cond>) {
$slnContent = <rest>
$NewslnContent = "content"
$pathOut = Join-Path -Path 'C:\Devjobs\clonefolder' -ChildPath $repo.name
# first create the folder path if it does not exist already
$null = New-Item -Path $pathOut -ItemType Directory -Force
# now write the file
$NewslnContent | Set-Content -Path (Join-Path -Path $pathOut -ChildPath $srccontent.name)
}
}
uj5u.com熱心網友回復:
您可能想嘗試Join-Path跨平臺而不是字串連接。話雖如此,如果您使用的是 Windows 機器,這不太可能是您的問題。
您可能希望用于Test-Path驗證路徑和檔案是否已經存在。
$path = 'C:' |
Join-Path -ChildPath 'Devjobs' |
Join-Path -ChildPath 'clonefolder' |
Join-Path -ChildPath $repo.name
$filepath = $path | Join-Path -ChildPath $srccontent.name
If (-Not (Test-Path $path)) {
New-Item -Type Directory -Path $path
}
If (-Not (Test-Path $filepath)) {
Remove-Item -Path $filepath
}
$FileContent | Out-File $filepath
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412498.html
標籤:
上一篇:C 程式中變數名存盤在哪里?
