将变量内容导出到文件

Export Variable contents to file

我在 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

您可能想要尝试跨平台 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

正如 已经评论的那样,错误显示 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)

通过在 New-Item 上使用 -Force 开关,您将创建目录,或者如果文件夹已经存在则返回 DirectoryInfo 对象。
在这种情况下,我们不再需要该对象,所以我们用 $null =.

丢弃它

请注意,这仅在文件系统上有效,如果您对注册表项执行相同的操作,您将丢失现有项的所有内容!

注意:我使用 Set-Content 而不是 Out-File,因为在 5.1 及更高版本的 PowerShell 中,不使用 -Encoding 参数的 Out-File 会将文件写入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)
    }
}