简体   繁体   中英

Powershell ForEach-Object output

More of a basic question but I can't seem to get the syntax correct. I am trying to go through a list and then output the Computer Name and BDE status with it.

Get-Content 'C:\Users\Test\Test\IT\Lists\LaptopList.txt' | ForEach-Object { write-host "***" | manage-bde -status }

Is there something I need to put where the *'s are so that it correlates with the computer/object and the status?

Thanks!

Is there something I need to put where the *'s are so that it correlates with the computer/object and the status?

Yes! You're looking for $_ :

Get-Content 'C:\Users\Test\Test\IT\Lists\LaptopList.txt' | ForEach-Object { 
    Write-Host $_
}

As the name indicates, Write-Host writes output directly to the host application - in the case of powershell.exe it writes directly to the screen buffer - which means it doesn't output anything to downstream cmdlets in a pipeline statement like the one you've constructed.

You'll therefore want two separate statements:

Get-Content 'C:\Users\Test\Test\IT\Lists\LaptopList.txt' | ForEach-Object { 
    Write-Host $_
    manage-bde -status
}

Now, manage-bde is not a PowerShell cmdlet - it's a windows executable, and it doesn't support managing remote computers.

So we need something in PowerShell that can run manage-bde on the remote machine - my choice would be Invoke-Command :

Get-Content 'C:\Users\Test\Test\IT\Lists\LaptopList.txt' | ForEach-Object { 
    Write-Host "Remoting into $_ to fetch BitLocker Drive Encryption status
    Invoke-Command -ComputerName $_ -ScriptBlock { manage-bde -status }
}

Here, we instruct Invoke-Command to connect to the computer with whatever name is currently assigned to $_ , and then execute manage-bde -status on the remote machine and return the resulting output, if any. Assuming that WinRM/PowerShellRemoting is configured on the remote machines, and the user executing this code locally is a domain account with local admin privileges on the remote computers, this will work as-is.

Further reading:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM