gpt4 book ai didi

powershell - Powershell笔录-输出到文件且不在控制台中显示

转载 作者:行者123 更新时间:2023-12-02 23:52:57 25 4
gpt4 key购买 nike

我正在编写PowerShell脚本以收集服务器上的常规信息。我编写了脚本,以便通过PowerShells Start-Transcript cmdlet将其输出到名为output.txt的文件。输出正常。但是,我只希望输出在文件中,而不显示在控制台上。

我一直在寻找并尝试查看Start-Transcription是否可以抑制控制台输出,但是我什么都没找到。

这是我使用的代码的精简版本-

Start-Transcript -path "Path\To\Output\File.txt"
$servers = Get-Content -path "Path\To\Servers\List\file.txt"
foreach ($server in $servers)
{
net view
net use
net session
}
Stop-Transcript

所有这些都正确输出到文件,但是我只希望它不在控制台中显示脚本/命令结果。如果可能的话。

最佳答案

这行得通吗?

$FilePath = 'Path\To\Output\File.txt'

net view | Out-File -FilePath $FilePath
net use | Out-File -FilePath $FilePath -NoClobber -Append
net session | Out-File -FilePath $FilePath -NoClobber -Append

或 bundle 它:
Invoke-Command {net view ; net use ; net session} | Out-File -FilePath $FilePath -NoClobber -Append

基于评论进行编辑(但可以从iPhone的内存中自由写入,因此可能会出现一些小错误):
要针对服务器列表远程运行此功能,您首先要在服务器上启用Powershell远程处理,这有很多方法,以下是在每台服务器上的本地Powershell session 中运行的一种方法(Runas Admin):
winrm quickconfig

然后,假设它们都具有相同的登录名,则可以:
$Cred = Get-Credential
$Servers = ’server1.example.com’,’server2.example.com’

Invoke-Command -ComputerNames $Servers -Credential $Cred -ScriptBlock {
Do stuff
Do some other stuff
} | Out-File -FilePath $FilePath -NoClobber -Append

结果以数组形式返回,因此,如果要按服务器分隔输出,可以尝试:
$a = Invoke-Command [...]etc but skip the |Out-File

然后做一些本质上就是这部分的循环,在这里为您提供手动方式:
$a[0] | Out-File -FilePath $FilePath1 -NoClobber -Append #result from first computer
$a[1] | Out-File -FilePath $FilePath2 -NoClobber -Append #result from second computer
...

和一个示例循环:
$a | Foreach-Object {$_ | Out-File -FilePath $Path -Append -NoClobber}

为了从文本文件中读取服务器名称,每行一个服务器名称:
$Servers = Get-Content -Path ’C:\temp\example.txt’
Invoke-Command -ComputerName $Servers [...]etc

关于powershell - Powershell笔录-输出到文件且不在控制台中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54427481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com