Show tabular output in richtextbox - winforms

Just installed the PowerShell Studio and I'm trying to view the results of some VMware commands in a richtextbox.
When I run the get-vm, for example, it shows the data fine (I changed the font to Lucida Console- and it looks ok), regular get-vm results in the richtext box:
Name : xxx
Cluster : xxx
ESX Host : esx6
Datastore : xxx
MemoryGB : 8
NumCpu : 2
ProvisionedSpace(GB) : 282
UsedSpace(GB) : 281
OS : Microsoft Windows Server 2008 R2 (64-bit)
But when I try to run (get-vm).Guest.Disks the data not shown good in the richtextbox, it looks like this:
Capacity:192515403776,
FreeSpace:43895230464,
Path:E:\
Capacity:75053920256,
FreeSpace:12630409216,
Path:C:\
when run it in regular powershell console it look like it should:
Volume Capacity(GB) FreeSpace(GB) % FreeSpace
------ ------------ ------------- -----------
E:\ 120 13 11
C:\ 120 15 12
The command line in PowerShell is:
((Get-VM $vm).Guest.disks) | Format-Table #{N="Volume";E={$_.Path}},
#{N="Capacity(GB)";E={[System.Math]::Round($_.CapacityGB)};a="left"},
#{N="FreeSpace(GB)";E={[System.Math]::Round($_.FreeSpaceGB)};a="left"},
#{N="% FreeSpace";E={[math]::Round((100 * ($_.FreeSpacegb / $_.Capacitygb)),0)};a="left"} -auto |
Out-String
the command line in the richtextbox is:
$richtextbox1.AppendText((Get-VM $text).Guest.disks) |
Format-Table #{N="Volume";E={$_.Path}},
#{N="Capacity(GB)";E={[System.Math]::Round($_.CapacityGB)};a="left"},
#{N="FreeSpace(GB)";E={[System.Math]::Round($_.FreeSpaceGB)};a="left"},
#{N="% FreeSpace";E={[math]::Round((100 * ($_.FreeSpacegb / $_.Capacitygb)),0)};a="left"} -auto |
Out-String
How can I get the results like it looks in the PowerShell console wheter is with richtextbox or any other control?

Looks like your richtextbox gives you the results in list format. Pipe your results into the Format-Table cmdlet before piping it into Out-String to enforce table format:
... | Format-Table | Out-String

You need to use one of the following fixed size fonts to display the output:
Consolas
Courier New
Lucida Console

Related

Powershell Array Enumeration to Log

I am attempting to enumerate an array of certificates to a log file:
$allCerts = Get-ChildItem Cert:\LocalMachine\My\ | Select-Object name,subject,Thumbprint,Issuer,NotAfter
Then sending to log via logging function:
$allCerts | ForEach-Object {logger -logstr $_}
This shows the following in the log (sensitive info removed) - note the log isn't wrapped, this is one line for each cert:
[2020-0326-1003:11:10] : #{name=; Subject=CN=WinRM HTTPS mycomputer; Thumbprint=12345679679484747463etygvetevtreye; Issuer=CN=WinRM HTTPS computer; NotAfter=03/26/2023 09:38:09}
[2020-0326-1003:11:11] : #{name=; Subject=CN=mycompcert2.abc.de.fg; Thumbprint=fdhshs44he4hhh4the44h4h4; Issuer=CN=Enterprise CA, OU=Cert Svcs, O=A Corporation, L=location, S=state, C=AU; NotAfter=09/20/2050 10:30:00}
The only way I've found so far is to:
$allCerts | ForEach-Object {logger -logstr ($_ | Out-String)}
Which gives:
[2020-0326-0952:11:56] :
name :
Subject : CN=WinRM HTTPS mycomputer
Thumbprint : 12345679679484747463etygvetevtreye
Issuer : CN=WinRM HTTPS computer
NotAfter : 03/26/2023 09:38:09
[2020-0326-0952:11:57] :
name :
Subject : CN=mycompcert2.abc.de.fg
Thumbprint : fdhshs44he4hhh4the44h4h4
CN=Enterprise CA, OU=Cert Svcs, O=A Corporation, L=location, S=state, C=AU
NotAfter : 09/20/2050 10:30:00
Is there a "tidier" way I can enumerate the properties of each member of the array to a single line in the log without having to use | out-string?
your Logger function seems to require a string. so you need to build the string 1st. the default .ToString() method will not give you what you want, tho.
you can do a slightly iffy trick and use ConvertTo-CSV to give you the lines that would be in a CSV file ... and skip the 1st line to get rid of the header line. something like the following ...
[my cert list for the machine has no certs, so i used the current user. also, i have no Name property ... only a FriendlyName property.]
Get-ChildItem Cert:\CurrentUser\My |
Select-Object -Property FriendlyName, Subject, Thumbprint, Issuer, NotAfter |
ConvertTo-Csv -Delimiter ';' -NoTypeInformation |
Select-Object -Skip 1
output ...
"APNS certificate";"CN=95F066ED-5A55-4053-84A0-D49E72C4AF6B";"42DA37600AFD9F0423FDCCF298A89C6CF1F945C8";"CN=Apple iPhone Device CA, OU=Apple iPhone, O=Apple Inc., C=US";"2016-11-03 2:18:59 PM"
"APNS certificate Direct";"CN=8E9D6C89-2BEF-4677-A9AD-84645ABFE44A";"2580F9FD8CB5E49EAC1035940D0D8EC09746A078";"CN=Apple iPhone Device CA, OU=Apple iPhone, O=Apple Inc., C=US";"2019-12-09 3:39:44 AM"
if you want to strip out the quotes, that seems fairly easy. [grin]

PowerCLI vSphere set-annotation

I am able to set notes in annotation with below PowerCLI vSphere.
Input: serverdetails.txt
name,notes
Server 1, This is an application server : .Net
Command:
Import-Csv "C:\temp\serverdetails.txt" | %{ Set-Vm -Name $.Name -Description $.Name -Confirm:$false }
Current Output in annotation i get is as below, complete content in one line.
This is an application server : .Net
However, i need below output in annotation (in two lines):
Line 1: This is an application server
Line 2: .Net
That's not really how the notes field operates, it's more designed around displaying information in the multi-VM view where multi-line output wouldn't work.
If you're looking for something that can display multiple lines, in an prescriptive manner, look at using Tags or even Annotations/Custom Attributes.

Download all SSRS reports

I want to get a copy of all .rdl files in one server.
I can do the download manually one report at the time, but this is time consuming especially that this server has around 1500 reports.
Is there any way or any tool that allows me to download all the .rdl files and take a copy of them?
There is a complete & simpler way to do this using PowerShell.
This code will export ALL report content in the exact same structure as the Report server. Take a look at the Github wiki for other options & commands
#------------------------------------------------------
#Prerequisites
#Install-Module -Name ReportingServicesTools
#------------------------------------------------------
#Lets get security on all folders in a single instance
#------------------------------------------------------
#Declare SSRS URI
$sourceRsUri = 'http://ReportServerURL/ReportServer/ReportService2010.asmx?wsdl'
#Declare Proxy so we dont need to connect with every command
$proxy = New-RsWebServiceProxy -ReportServerUri $sourceRsUri
#Output ALL Catalog items to file system
Out-RsFolderContent -Proxy $proxy -RsFolder / -Destination 'C:\SSRS_Out' -Recurse
I've created this powershell script to copy them into a ZIP. You have to provide the SQL server database details.
Add-Type -AssemblyName "System.IO.Compression.Filesystem"
$dataSource = "SQLSERVER"
$user = "sa"
$pass = "sqlpassword"
$database = "ReportServer"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pass;Database=$database;Integrated Security=False;"
$tempfolder = "$env:TEMP\Reports"
$zipfile = $PSScriptRoot + '\reports.zip'
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$allreports = $connection.CreateCommand()
$allreports.CommandText = "SELECT ItemID, Path, CASE WHEN Type = 2 THEN '.rdl' ELSE '.rds' END AS Ext FROM Catalog WHERE Type IN(2,5)"
$result = $allreports.ExecuteReader()
$reportable = new-object "System.Data.DataTable"
$reportable.Load($result)
[int]$objects = $reportable.Rows.Count
foreach ($report in $reportable) {
$cmd = $connection.CreateCommand()
$cmd.CommandText = "SELECT CAST(CAST(Content AS VARBINARY(MAX)) AS XML) FROM Catalog WHERE ItemID = '" + $report[0] + "'"
$xmldata = [string]$cmd.ExecuteScalar()
$filename = $tempfolder + $report["Path"].Replace('/', '\') + $report["Ext"]
New-Item $filename -Force | Out-Null
Set-Content -Path ($filename) -Value $xmldata -Force
Write-Host "$($objects.ToString()).$($report["Path"])"
$objects -= 1
}
Write-Host "Compressing to zip file..."
if (Test-Path $zipfile) {
Remove-Item $zipfile
}
[IO.Compression.Zipfile]::CreateFromDirectory($tempfolder, $zipfile)
Write-Host "Removing temporarly data"
Remove-Item -LiteralPath $tempfolder -Force -Recurse
Invoke-Item $zipfile
If you just need this for backup purposes or something similar, this might be useful: Where does a published RDL file sit?
The relevant query from that thread is:
select convert(varchar(max), convert(varbinary(max), content))
from catalog
where content is not null
The original answer was using 2005, and I've used it on 2016, so I imagine it should work for 2008 and 2012.
When I had to use this, I added in the Path to the query as well, so that I knew which report was which.
CAVEAT: prior to SSMS v18, Results to Grid is limited to 64KB per tuple and Results to Text are limited to 8,192 characters per tuple. If your report definition is larger than these limits you will not be able to get the entire definition.
In SSMS v18, those limits have been increased to 2MB per tuple for both Reports to Grid as well as Results to Text.
This is based on SQL2016/SSRS2016 but I think it should work for 2012.
SELECT 'http://mySQLServerName/reports/api/v1.0/catalogitems(' + cast(itemid as varchar(256))+ ')/Content/$value' AS url
FROM ReportServer.dbo.Catalog
This will give you a list of URL's, one for each report.
If the above did not work in SSRS 2012 then go to the report manager and do as if you were going to download the file from there. Check the URL on the download button and you'll probably see a URL with and item id embedded int it. Just adjust the above code to match that url structure.
What you do with then after this is up to you.
Personally I would use the Chrome extension called 'Tab Save' available in the Chrome store here. You can simply copy and paste all the URL's created above into it and hit the download button...
Found and used this without any issues. Nothing to install, just added my url, and pasted into Powershell.
https://microsoft-bitools.blogspot.com/2018/09/ssrs-snack-download-all-ssrs-reports.html
In case the link breaks, here's the code from the link:
###################################################################################
# Download Reports and DataSources from a SSRS server and create the same folder
# structure in the local download folder.
###################################################################################
# Parameters
###################################################################################
$downloadFolder = "c:\temp\ssrs\"
$ssrsServer = "http://myssrs.westeurope.cloudapp.azure.com"
###################################################################################
# If you can't use integrated security
#$secpasswd = ConvertTo-SecureString "MyPassword!" -AsPlainText -Force
#$mycreds = New-Object System.Management.Automation.PSCredential ("MyUser", $secpasswd)
#$ssrsProxy = New-WebServiceProxy -Uri "$($ssrsServer)/ReportServer/ReportService2010.asmx?WSDL" -Credential $mycreds
# SSRS Webserver call
$ssrsProxy = New-WebServiceProxy -Uri "$($ssrsServer)/ReportServer/ReportService2010.asmx?WSDL" -UseDefaultCredential
# List everything on the Report Server, recursively, but filter to keep Reports and DataSources
$ssrsItems = $ssrsProxy.ListChildren("/", $true) | Where-Object {$_.TypeName -eq "DataSource" -or $_.TypeName -eq "Report"}
# Loop through reports and data sources
Foreach($ssrsItem in $ssrsItems)
{
# Determine extension for Reports and DataSources
if ($ssrsItem.TypeName -eq "Report")
{
$extension = ".rdl"
}
else
{
$extension = ".rds"
}
# Write path to screen for debug purposes
Write-Host "Downloading $($ssrsItem.Path)$($extension)";
# Create download folder if it doesn't exist (concatenate: "c:\temp\ssrs\" and "/SSRSFolder/")
$downloadFolderSub = $downloadFolder.Trim('\') + $ssrsItem.Path.Replace($ssrsItem.Name,"").Replace("/","\").Trim()
New-Item -ItemType Directory -Path $downloadFolderSub -Force > $null
# Get SSRS file bytes in a variable
$ssrsFile = New-Object System.Xml.XmlDocument
[byte[]] $ssrsDefinition = $null
$ssrsDefinition = $ssrsProxy.GetItemDefinition($ssrsItem.Path)
# Download the actual bytes
[System.IO.MemoryStream] $memoryStream = New-Object System.IO.MemoryStream(#(,$ssrsDefinition))
$ssrsFile.Load($memoryStream)
$fullDataSourceFileName = $downloadFolderSub + "\" + $ssrsItem.Name + $extension;
$ssrsFile.Save($fullDataSourceFileName);
}
I'vr tried several permutations of this script and keep getting the "can't create proxy connection" error. Here's the one that "should" work:
#------------------------------------------------------
#Prerequisites
#Install-Module -Name ReportingServicesTools
#------------------------------------------------------
#Lets get security on all folders in a single instance
#------------------------------------------------------
#Declare SSRS URI
$sourceRsUri = "http://hqmnbi:80/ReportServer_SQL08/ReportService2010.asmx?wsdl"
#Declare Proxy so we dont need to connect with every command
$proxy = New-RsWebServiceProxy -ReportServerUri $sourceRsUri
#Output ALL Catalog items to file system
Out-RsFolderContent -Proxy $proxy -RsFolder / -Destination 'C:\Users\arobinson\source\Workspaces\EDW\MAIN\SSRS\HQMNBI' -Recurse
This is the error I'm getting:
Failed to establish proxy connection to http://hqmnbi/ReportServer_SQL08/ReportService2010.asmx : The HTML document does not contain
Web service discovery information.
At C:\Program Files\WindowsPowerShell\Modules\ReportingServicesTools\0.0.6.6\Functions\Utilities\New-RsWebServiceProxy.ps1:136 char:9
throw (New-Object System.Exception("Failed to establish proxy ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [], Exception
FullyQualifiedErrorId : Failed to establish proxy connection to http://hqmnbi/ReportServer_SQL08/ReportService2010.asmx : The
HTML document does not contain Web service discovery information.
I've tried the URI with htttp:// and without, I've tried including the port number. etc. Still can't get this to actually work. We have two other SSRS instances that I was able to run this against no problem.
From this question: SQL Reporting Services - COPY reports to another folder
I found this tool can both download and upload reports. Plus it lists out folders and subfolders.
http://code.google.com/p/reportsync/

How to find the client name who has logged in to machine?

We are trying to find from which machine a user has taken rdp .
Using "quser" utility we are able to get all the information about logged in user except client name.
Following is the command
function Get-LoggedOnUser
{
param([String[]]$ComputerName = $env:COMPUTERNAME)
$ComputerName | ForEach-Object {
(quser /SERVER:$_) -replace '\s{2,}', ',' |
ConvertFrom-CSV |
Add-Member -MemberType NoteProperty -Name ComputerName -Value $_ -PassThru
}
}
It displays all the information which can be provided in Windows task manager except client Name .
How to get client Name using powershell?
I doubt if WMI has a way to do this. You can check the PSTerminal Services module and it has a Get-TSSession cmdlet which does the same job you are looking for.
http://archive.msdn.microsoft.com/PSTerminalServices
This module uses binary Cassia namespace.
You can use this:
http://gallery.technet.microsoft.com/scriptcenter/0e43993a-895a-4afe-a2b2-045a5146048a
and look for the logged on user with a logon type of RemoteInteractive
You can read that information from the Security eventlog (look for logon type 10):
$username = '...'
$eventID = 4624 # 526 on Server 2003 and earlier
$date = (Get-Date).Date
$pattern = 'logon type:\s+10[\s\S]+source network address:\s+(\S+)'
Get-EventLog Security -InstanceId $eventID -EntryType SuccessAudit `
-After $date -Message '*$username*' `
| ? { $_.Message -match $pattern } `
| % { $matches[1] } `
| select -Unique
Note that on Server 2003 and earlier you need to check for event ID 528 instead of 4624.
References:
http://technet.microsoft.com/en-us/library/cc787567
http://support.microsoft.com/kb/977519

How can I branch "main" node of a UCM project?

We're using RAD with ClearCase plugin as "ClearCase Explorer Perspective". I need to make a new main version of a java project. For that reason, I want to change main/0 version to ie. main/1. How can I forward version from top-level? I tried to make new project by using "Project Explorer" creating new stream. It required previous baselines. However, when I checkin from this new project stream, it branches from the given baseline version(say 1) like below.
main
|
0
|
MyProj1_Integration
|
0
|
1(BL)---MyProj2_Integration
| |
2 0
|
1
I want it to be like:
main
0 ------------------- 1
| |
MyProj1_Integration MyProj2_Integration
| |
0 0
| |
1(BL 1
|
2
When inspecting versions from ClearCase Explorer version numbers are shown like below:
/main/MyProj1_Integration/MyProj2_Integration/1
I expect to see:
/main/MyProj2_Integration/1
Also, I want to include latest versions of files from previous branch to the new branch.
How can I achieve that? Do I need to create a new VOB?
/main/0 is only accessible from the 'INITIAL' baseline.
That means you need to have on your MyProj2_Integration an baseline ending with _INITIAL.
Only that foundation baseline will branch from /main/0.
Once you have that configuration, you will then be able to make a 'deliver' from 'MyProj1_Integration' to 'MyProj2_Integration', in order to get back the latest versions of your first project in the new branch 'MyProj2_Integration'.

Resources