Home > Back-end >  Output to file in powershell
Output to file in powershell

Time:08-27

I want to output some information about devices to .txt file but something went wrong. Could someone tell me what the problem is?

   $devices=("wsu1","wsu2")
$file="C:\reports\file.txt"
 Invoke-Command -ComputerName $devices -ScriptBlock {
Get-WmiObject Win32_OperatingSystem |
Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber | Out-File -FilePath $file
}
 & explorer.exe "C:\reports\"

I retrieve this message from the console:

Cannot bind argument to parameter 'FilePath' because it is null.
      CategoryInfo          : InvalidData: (:) [Out-File], ParameterBindingValidationException
      FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand

CodePudding user response:

  • Your immediate problem is that you tried to access a local variable, $file in a remotely executing script block, which cannot work, and defaults to $null, causing Out-File to report an error due to lack of an output file name.

    • In any script block that runs in a different runspace (notably remotely, on other machines), you need to the $using: scope in order to use local variable values, such as $using:file in this case - see this answer for details.
  • However, the fact that you're executing & explorer.exe "C:\reports\" in an attempt to show the output file implies that you meant to write to a local file, which necessitates calling Out-File locally, outside the remote script block ({ ... }), in a separate pipeline segment.

    • Note that this approach - piping to a single Out-File call - ensures that all output from the Invoke-Command call, across all computers targeted, is saved to the output file; see this answer for more information.
devices = "wsu1", "wsu2"
$file = "C:\reports\file.txt"

# Note the placement of the Out-File call.
Invoke-Command -ComputerName $devices -ScriptBlock {
    Get-WmiObject Win32_OperatingSystem |
      Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber
  } |
  Out-File -FilePath $file

& explorer.exe "C:\reports\"

CodePudding user response:

This might help... maybe... :)

# Prep some stuff
$Devices = @("wsu1","wsu2")
$File = "C:\reports\file.txt"
$Results = @()

# Work for each device
foreach ($Device in $Devices) {
    $Results  = Invoke-Command -ComputerName $Device -ScriptBlock {
        Get-WmiObject Win32_OperatingSystem | Select-Object PSComputerName, Caption, OSArchitecture, Version, BuildNumber
    }
}

# Chuck it in a file
Set-Content -Value $Results -Path $File
  • Related