Hi All,
I am running below
foreach ($snap in Get-VM | Get-Snapshot)
{$snapevent = Get-VIEvent -Entity $snap.VM -Types Info -Finish $snap.Created -MaxSamples 1 | Where-Object {$_.FullFormattedMessage -imatch 'Task: Create virtual machine snapshot'}
if ($snapevent -ne $null){Write-Host ( "VM: "+ $snap.VM + ". Snapshot '" + $snap + "' created on " + $snap.Created.DateTime + " by " + $snapevent.UserName +".")}
else {Write-Host ("VM: "+ $snap.VM + ". Snapshot '" + $snap + "' created on " + $snap.Created.DateTime + ". This event is not in vCenter events database")}}
Now that o/p i need to put in a txt file.
In putty we ca log the session o/p to a file. Is there anyway to do same here with powercli cmd ?
Thanks,
Kiran
The issue here is that you are using Write-Host to present the result on the console.
The disadvantage of Write-Host is that it doesn't write to the pipeline but directly to the console.
One solution is to use Write-Output instead, or even better use the Select-Object cmdlet to select the properties you want to capture.
Get-VM | Get-Snapshot |
Select @{N="VM";E={$_.VM.Name}},
@{N="Snapshot";E={$_.Name}},
@{N="CreationDate";E={$_.Created}},
@{N="User";E={
$snapevent = Get-VIEvent -Entity $snap.VM -Types Info -Finish $snap.Created -MaxSamples 1 | Where-Object {$_.FullFormattedMessage -imatch 'Task: Create virtual machine snapshot'}
if($snapevent){$snapevent.UserName}
else{"This event is not in vCenter events database"}
}}
If you want to format the result in a specific text format, you can use the pipeline to send the resulting objects to another cmdlet.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
hi,
I use some small functions
function WriteToFile($message, $locationFile)
{
$message | out-file -encoding ascii $locationFile -Append
}
function WriteProgress($progress, $ForeGround, $progressFile)
{
if($ForeGround -eq $null)
{
$ForeGround = $Information;
}
$LogDate = Get-Date -uformat "%Y-%m-%d %H:%M:%S"
$message = $LogDate + " " + $progress
WriteToFile $message $progressFile;
Write-Host $LogDate " " $progress -ForegroundColor $ForeGround;
}
just replace write-host with WriteProgress, you get output both on screen and file.
PS: there are better ways of doing this as Luc mentioned.