Powershell: tablet output to string of lines with one space - string

$allSoftwareObj = Get-WmiObject -Class Win32_Product | Select-Object -Property Name, Version | ft -HideTableHeaders | ft -Wrap -AutoSize -Property Name, Version
$allSoftware = Out-String -InputObject $allSoftwareObj
echo $allSoftware
When I output this, I get a table structure. I don't want that.
How to get a new line per new output with only space between the Name and Version?
Wrong output now:
Microsoft SQL Server System CLR Types 10.51.2500.0
SQL Server 2012 Client Tools 11.1.3000.0
Wanted output:
Microsoft SQL Server System CLR Types 10.51.2500.0
Or:
Microsoft SQL Server System CLR Types (10.51.2500.0)

Try replacing the whole line with this:
Get-WmiObject -Class Win32_Product | % {"$($_.Name) ($($_.Version))"}

$allSoftwareObj = Get-WmiObject -Class Win32_Product | %{ $_.Name + " " + $_.Version}
$allSoftwareObj

You can do it like this:
Get-WmiObject -Class Win32_Product | Select-Object -Property Name, Version | % { write-host "$($_.name) ($($_.version))" }

Related

Display Data on Two Columns Within Excel

I am trying to display data within an Excel document where Column A displays the server name and column B displays the .NET version. I'm running into an issue exporting to a .csv because it says that the file path does not exist. I would like some guidance on how I can resolve that issue and how I can display data on the two columns within Excel.
$Servers =
(
"test"
)
foreach ($Server in $Servers)
{
Invoke-Command -ComputerName $Server -ScriptBlock {
Write-Output "$(hostname)"
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version,Release -EA 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChildName, Version, Release | Select -ExpandProperty Version | Sort-Object Version | Export-Csv -Path C:\Users\User\Desktop\example.csv
}
The main issue is that you're using Export-Csv on the remote hosts since it is inside the Invoke-Command script block, and the likeable error is because the path you are using as export doesn't exist on those hosts.
It's also worth noting that Invoke-Command can run in parallel, -ComputerName as well as -Session can take an array, this removes the need for the foreach loop as well as it is much faster / efficient.
Invoke-Command -ComputerName $servers -ScriptBlock {
Write-Host "Working on $($env:COMPUTERNAME)..."
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
Get-ItemProperty -Name Version, Release -EA 0 |
ForEach-Object {
if($_.PSChildName -notmatch '^(?!S)\p{L}') {
return # skip this
}
[pscustomobject]#{
HostName = $env:COMPUTERNAME
Version = $_.Version
}
} | Sort-Object Version
} -HideComputerName | Select-Object * -ExcludeProperty RunspaceID |
Export-Csv -Path C:\Users\User\Desktop\example.csv -NoTypeInformation

Azure Powershell - Script to obtain VM info across subscriptions

Trying to run a script that will connect to each subscription, and pull the
$azureSubs = Get-AzureRMSubscription
$azureSubs | ForEach-Object {Select-AzureRMSubscription $_ | Out-Null; Get-AzureRMVM | select resourcegroupname, name, licensetype -WarningAction SilentlyContinue}
This works, BUT I'd like to add two more pieces of information: the "OSType" and "VMSize"
If I do a GET-AZURERMVM, in the table for that subscription that the command is run in, the two pieces of information I need are there: VmSize and OsType
However, when I try to add them to the query, the columns are blank.
I believe the VmSize is in the HardwareProfile, and OsType is in the OsProfile, as if I run a "Get-AzureRMVM -name (name) -resourcegroupname (RGname)", then it shows "Hardware Profile: VMSize" and "OSProfile: ComputerName, AdminUsername windowsConfiguration, Secrets"
Ultimate goal is to get the script that will, for each subscription, print results like:
ResourceGroupName | Name | License Type | VMSize | OS Type
TEST_RG | Test_VM | Windows_Server | DS3_v2 | Windows
Test_RG | Test_VM2 | | DS3_v2 | Linux
etc.
Thankful for any help; sorry for such a noob question. Have spent so much time trying to figure this out...
Something like the following would work.
What you were missing mainly was calculated properties.
This is what allow you to perform a select of custom property.
Some notes:
In your code, you used -WarningAction SilentlyContinue on the Select statement. You need to put it on the Get-AzureRMVM CmdLet instead.
This is my opinion but unless you are writing one-liners on purposes, try aerating your code more. It will make it way easier to read, debug and maintain.
This is the code you wrote, modified to include the calculated properties and with the WarningAction parameter set to Get-AzureRMVM instead of the Select statement.
$azureSubs = Get-AzureRMSubscription
$Vms = $azureSubs | ForEach-Object {Select-AzureRMSubscription $_ | Out-Null; Get-AzureRMVM -WarningAction SilentlyContinue | select resourcegroupname, name, licensetype, #{Name="VMSize";Expression={$_.HardwareProfile.VmSize}},#{Name="OsType";Expression={$_.StorageProfile.OsDisk.OsType}}}
$Vms | ft
The same thing, with some progress indication without forcing everything on one line.
$azureSubs = Get-AzureRMSubscription
$Vms = New-Object 'System.Collections.Generic.List[PSObject]'
ForEach ($sub in $azureSubs) {
Select-AzureRMSubscription $sub | Out-Null
Write-Host "Processing Subscription $($sub.Name)".PadRight(50,' ') -ForegroundColor Cyan -NoNewline
[PsObject[]]$items = Get-AzureRMVM -WarningAction SilentlyContinue |
select resourcegroupname,
name,
licensetype,
#{Name="VMSize";Expression={$_.HardwareProfile.VmSize}},
#{Name="OsType";Expression={$_.StorageProfile.OsDisk.OsType}}
Write-Host "($($items.count) retrieved)"
if ($items -ne $null) {
$vms.AddRange($items)
}
}
$vms | Format-Table
You are looking for something like this on the select side
select resourcegroupname, name, licensetype, #{Name="VMSize";Expression={$_.HardwareProfile.VmSize}}, #{Name="OsType";Expression={$_.StorageProfile.OsDisk.OsType}}

How can I split AD information in Powershell into a excel document?

I am a Powershell starter. I have been trying to create a script, that makes an Excel file with some AD information including the DistinguishedName. My script looks like this:
$dn = Get-ADUser -Filter * -SearchBase "OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads" | select DistinguishedName,SamAccountName,name |export-csv C:\temp\test1.csv -Delimiter ";"
An example of what I get (Note: | means new cell in Excel):
CN=Testuser\, Verfluecht,OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads | vtestuser | Testuser, Verfluecht
But in order to group the paths in excel, I need it without the CN (CN=Testuser\, Verfluecht,)
So that it would look like this:
OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads | vtestuser | Testuser, Verfluecht
How can I do this?
I tried many things such as .substring and replace, but I could not get it done.
Using this link and a calculated property, it should just drop the first part of the distinguishedname and be left with the parts you need.
Get-ADUser -Filter * -SearchBase "OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads" |
Select-Object #{Name="DistinguishedName";Expression={$_.distinguishedname | ForEach-Object {$_ -replace '^.+?(?<!\\),',''}}},samaccountname,name |
Export-Csv C:\temp\test1.csv -Delimiter ";"
On my test environment, I get the output below (without piping it to Export-Csv).
Get-ADUser -Filter * | Select-Object #{Name="DistinguishedName";Expression={$_.distinguishedname | ForEach-Object {$_ -replace '^.+?(?<!\\),',''}}},samaccountname,name
DistinguishedName samaccountname name
----------------- -------------- ----
CN=Users,DC=timhaintz,DC=com Administrator Administrator
CN=Users,DC=timhaintz,DC=com Guest Guest
CN=Users,DC=timhaintz,DC=com DefaultAccount DefaultAccount
CN=Users,DC=timhaintz,DC=com krbtgt krbtgt
Thanks, Tim.

How to export output of batch file/Powershell Script in a Excel Spreadsheet

I have been asked to go around the entire building and document the serial numbers, and system information on all of the PC's in the network. As I was doing it I realized that I could of just wrote a batch file or Powershell Script to do this for me. I typed in the command "wmic bios get serialnumber" and it gave me the serial number for my machine. Is there a way to Get all of the information such as the processor, memory, ip address, and serial number and output it in a excel spreadsheet ? If it can only be exported in a text file that is fine. I would like to save it on my server. I don't know how I can save it all to one text file. I realize that I could have the batch file make a text file of its own with the >> %COMPUTERNAME%.txt command.
Any help or suggestions would be great!
Thanks!
Get-WmiObject win32_processor | Findstr ('Name') | Format-List
$env:COMPUTERNAME | Format-List
wmic bios get serialnumber /Format
Get-WmiObject -Class Win32_ComputerSystem | Findstr ('Model') | Format-List
Get-WmiObject -Class Win32_ComputerSystem | Findstr ('Manufacturer') | Format-List
Get-WmiObject -Class Win32_ComputerSystem | Findstr ('Name') | Format-List
(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim() | Format-List
Export-CSV -Path C:\Users\ars001\%COMPUTERNAME%.csv | Format-List
Ok, you evidently put in some effort to get the commands to at least gather the info and what classes you'd need for what details, so I'll give you this much...
$Computers = Get-Content C:\Path\To\ComputerList.txt
[array]$Results = $Record = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $PC | select Model,Manufacturer,Name,TotalPhysicalMemory
$Results[0] | Add-Member 'Processor' $(Get-WmiObject win32_processor -ComputerName $PC | % Name)
$Results[0] | Add-Member 'SerialNumber' $(Get-WmiObject bios -ComputerName $PC |% serialnumber)
ForEach($PC in $Computers){
If(!(Test-Connection $PC -Quiet) -or $PC -eq $env:COMPUTERNAME){Continue}
$Record = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $PC | select Model,Manufacturer,Name,TotalPhysicalMemory
$Record | Add-Member 'Processor' $(Get-WmiObject win32_processor -ComputerName $PC | % Name)
$Results += $Record | Add-Member 'SerialNumber' $(Get-WmiObject bios -ComputerName $PC |% serialnumber) -PassThru
}
$Results | Export-Csv c:\Path\To\Output.csv -NoTypeInformation
Then you just need to edit the paths, and have a list of computers saved as a text file. If you have the AD module installed you can query AD for that info instead.

Can not convert output to string

I cannot format this command to string. The code below returns $r as an empty string. Why?
$f = gwmi -ComputerName PCname -Class Win32_Process -Filter "name='process.exe'"|
select {$_.WorkingSetSize/1MB}|fl
$r = $f.ToString()
If you check the object type returned by Format-List you will see that it is an array of System.Object.
$f = gwmi -ComputerName PCname -Class Win32_Process -Filter "name='process.exe'"| `
select {$_.WorkingSetSize/1MB}|fl
$r | get-member
If you just need the values of working set, try this:
gwmi -ComputerName PCname -Class Win32_Process -Filter "name='process.exe'" | `
select #{label='WorkingSetSize';expression={$_.WorkingSetSize/1MB}}| `
select -expandproperty WorkingSetSize
Format-List produces an array of strings, not a single string, so $f.ToString() should give you System.Object[]. To convert an array to a single string you can pipe it into the Out-String cmdlet:
$f = gwmi -ComputerName PCname -Class Win32_Process -Filter "name='process.exe'" |
select {$_.WorkingSetSize/1MB} | fl
$g = $f | Out-String
However, as mentioned above, you should at least get System.Object[], not an empty string, so double-check the value of $f.
What I find is that -Filter "name='process.exe'" does not work for me. So I substituted
| where {$_.name -match "Process"}
This is my result, I also substituted LocalHost for PCname and removed |fl
$r = gwmi -ComputerName localhost -Class Win32_Process | where {$_.name -match "Process"} |
select #{label='WorkingSetSize';expression={$_.WorkingSetSize/1MB}} |
select -expandproperty WorkingSetSize
$r.ToString()

Resources