删除 PowerShell 脚本块中的空格

问题描述 投票:0回答:1

我正在将一些脚本块写入文本文件,如下所示:

$scriptblock = ""

if (1 -eq 1) {
    if (2 -eq 2) {    
        $scriptblock = {
            try {
                $test = "This string contains spaces";
            } catch {
                $test = "So does this";
            }
        }
    }
}                                    
                                                
$scriptblock | out-file c:\temp\scriptblock.txt  

但是当我将其写入文本文件时,我最终得到了每行之前的所有空白。所以它看起来像这样:

            try {
                $test = "This string contains spaces";
            } catch {
                $test = "So does this";
            }

而不是这个:

try {
    $test = "This string contains spaces";
} catch {
    $test = "So does this";
}

如果我不缩进原始代码,它可能会起作用。但后来我失去了我的缩进。从编码的角度来看有什么办法可以做到这一点吗?谢谢。

powershell
1个回答
1
投票

更新:
我强烈建议使用我在底部原始答案中链接的模块。
但如果不可能,那就有一个非常快速、非常脏的函数

function Format-ScriptBlock {
    [CmdletBinding()]
    param (
        [parameter(Mandatory)]
        [scriptblock]$Script
    )
    
    
    process {
        # turns scriptblock in string array, removing all empty or whitespace-only lines
        $ScriptArray = $Script.ToString().Split("`n", [System.StringSplitOptions]::RemoveEmptyEntries).Where({ -not [string]::IsNullOrWhiteSpace($_) })

        # gets the base-indent of the first line
        $BaseIndent = $ScriptArray[0].Length - $ScriptArray[0].TrimStart().Length
        
        # remove the same amount of spaces from all the line
        $array -replace "^\s{$BaseIndent}", ''
    }
    
}

Format-ScriptBlock $scriptblock | Out-File '.\scriptblock.txt'

原文:

使用模块中的

Invoke-Formatter
PSScriptAnalyzer

$scriptblock |Invoke-Formatter | Out-File '.\scriptblock.txt'
© www.soinside.com 2019 - 2024. All rights reserved.