Powershell - 避免重复 Out-File 的参数
Powershell - avoid repeating arguments of Out-File
有什么方法可以避免将参数传递给函数,比如“-Append $outfile”到 Out-File,每次?我有一个从系统收集数据的脚本,比如:
... collect OS information ... | Out-File -Append $output
... collect local users ... | Out-File -Append $output
... collect logfile permissions ... | Out-File -Append $output
etc.
管道中的最后一个命令大部分时间都是 Out-File -Append $output
- 这可以做得更优雅吗?我有不同的想法:
创建一个 包装函数,它将所需的参数传递给 Out-File 命令 - 已经尝试过,但我在使其与管道兼容时遇到了问题
将所有输出写入 String-Variable 并将所有命令末尾的内容写入文件 - 需要大量内存
创建类似 Output-Writer-Object 的东西,它只在初始化时接收一次必要的参数 - 尚未尝试
非常感谢您的帮助!
你似乎没有使用很多参数,因为它非常有用,但一个好的建议是使用 splatting。我添加了一些更多的参数来说明它如何使代码在显示的同时仍能正常运行。
$options = @{
Append = $True
FilePath = $output
Encoding = "Unicode"
Width = 400
}
构建选项的 hastable 和splat带有它们的 cmdlet
... collect OS information ... | Out-File @options
... collect local users ... | Out-File @options
... collect logfile permissions ... | Out-File @options
除此之外,您建议的包装函数(如果更容易,则为过滤器)将是另一种选择。 Look at the options in this answer. Specifically the filter
您想使用 $PSDefaultParameterValues 首选项变量。像这样:
$PSDefaultParameterValues = @{
"Out-File:Encoding"="utf8";
"Out-File:Append"=$true;
"Out-File:FilePath"=$output
}
当您几乎每次使用该命令时都必须指定相同的备用参数值,或者当特定参数值难以记住时(例如电子邮件服务器名称或项目),此功能特别有用GUID.
或者将所有内容放入函数或脚本块中。注意 out-file 默认为 utf16 编码,并且可以混合编码,而不是 add-content.
& {
... collect OS information ...
... collect local users ...
... collect logfile permissions ...
} | add-content $output
有什么方法可以避免将参数传递给函数,比如“-Append $outfile”到 Out-File,每次?我有一个从系统收集数据的脚本,比如:
... collect OS information ... | Out-File -Append $output
... collect local users ... | Out-File -Append $output
... collect logfile permissions ... | Out-File -Append $output
etc.
管道中的最后一个命令大部分时间都是 Out-File -Append $output
- 这可以做得更优雅吗?我有不同的想法:
创建一个 包装函数,它将所需的参数传递给 Out-File 命令 - 已经尝试过,但我在使其与管道兼容时遇到了问题
将所有输出写入 String-Variable 并将所有命令末尾的内容写入文件 - 需要大量内存
创建类似 Output-Writer-Object 的东西,它只在初始化时接收一次必要的参数 - 尚未尝试
非常感谢您的帮助!
你似乎没有使用很多参数,因为它非常有用,但一个好的建议是使用 splatting。我添加了一些更多的参数来说明它如何使代码在显示的同时仍能正常运行。
$options = @{
Append = $True
FilePath = $output
Encoding = "Unicode"
Width = 400
}
构建选项的 hastable 和splat带有它们的 cmdlet
... collect OS information ... | Out-File @options
... collect local users ... | Out-File @options
... collect logfile permissions ... | Out-File @options
除此之外,您建议的包装函数(如果更容易,则为过滤器)将是另一种选择。 Look at the options in this answer. Specifically the filter
您想使用 $PSDefaultParameterValues 首选项变量。像这样:
$PSDefaultParameterValues = @{
"Out-File:Encoding"="utf8";
"Out-File:Append"=$true;
"Out-File:FilePath"=$output
}
当您几乎每次使用该命令时都必须指定相同的备用参数值,或者当特定参数值难以记住时(例如电子邮件服务器名称或项目),此功能特别有用GUID.
或者将所有内容放入函数或脚本块中。注意 out-file 默认为 utf16 编码,并且可以混合编码,而不是 add-content.
& {
... collect OS information ...
... collect local users ...
... collect logfile permissions ...
} | add-content $output