更新时间:2022-12-23 09:55:23
如果目标是让您自己选择输出到调用系统上的多个文件,您可以使用哈希表 ($results
) 在您的脚本块中以存储您的结果.然后在脚本块的末尾输出该表.根据这些键/值,您可以输出到文件.
If the goal is to give yourself the option to output to multiple files on the calling system, you could use a hash table ($results
) inside of your script block to store your results. Then output that table at the end of your script block. Based on those keys/values, you could output to file.
foreach ($computer in $computers) {
$Output = Invoke-Command -Computername $computer -Credential $credential {
$results = @{}
$computername = hostname.exe
If ($PSVersionTable.PSVersion -ge '4.0') {
If (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
$HyperV = Get-WindowsOptionalFeature -Online -FeatureName *Hyper-V* | Format-Table -AutoSize
if (Get-Command Get-VM -ErrorAction SilentlyContinue) {
$VMInfo = Get-VM | Format-Table -AutoSize
$VMNic = Get-VM | Get-VMNetworkAdapter | Format-Table -AutoSize
} else {
Write-Host -ForegroundColor Yellow " Hyper-V feature not installed on this host"
}
} else {
Write-Host -ForegroundColor Red " You do not have required permissions to complete this task ..."
}
} else {
Write-Host -ForegroundColor Red " This commands requires at least PowerShell 4.0 ... manual inspection is required"
}
$results.Add('HyperV',$HyperV)
$results.Add('VMInfo',$VMInfo)
$results.Add('VMNic',$VMNic)
$results
}
$Output.HyperV | Out-File -Width 1024 "c:\scripts\ComputerInformation\$computer.hyperv.txt"
$Output.VMInfo | Out-File -Width 1024 "c:\scripts\ComputerInformation\$computer.VMInfo.txt"
$Output.VMNic | Out-File -Width 1024 "c:\scripts\ComputerInformation\$computer.VMNic.txt"
}
如果目标是简单地将所有数据输出到一个位置,您可以简单地将您的 Invoke-Command
结果存储到一个变量中.然后将变量内容写入文件:
If the goal is to simply output all data to one location, you can simply store your Invoke-Command
result into a variable. Then write the variable contents to file:
$Output = Invoke-Command -Computername $computer -Scriptblock { # my code runs here }
$Output | Out-File "C:\Folder\$computer.txt"
如果您希望在变量中捕获 Write-Host
输出,则需要将信息流发送到成功流 ( { script block } 6>&1
}
If you are looking to capture Write-Host
output in a variable, you will need to send the information stream to the success stream ( { script block } 6>&1
}