Powershell - question about for each / variables - arrays

I have this simple question about my code. I would like to create an array for pushing my variables into database mssql.
My first problem is about the definitions of variables. The PowerShell ISE response to me is this error code:
You must provide a value expression following the '%' operator. I would like to understand how to correctly define the variables $CPUPer.CPU % and Memory (MB). I suppose it's a simple use of quotes on those properties, but i don't know what to do.
Next goal is to collect this variable and push into database table. I hope the code is correct but I probably need any suggestions.
This is an extract of my output in the array $CPUPercent :
Name CPU CPU % Memory (MB) Description
---- --- ----- ----------- -----------
dwm 1225.47 5.37 240.91796875 Desktop Window Manager
chrome 679.33 2.99 359.3828125 Google Chrome
chrome 497.44 2.19 251.390625 Google Chrome
chrome 393.58 2.15 415.515625 Google Chrome
$CPUPercent = #{Name='CPU %';Expression={$TotalSec=(New-TimeSpan -Start $_.StartTime).TotalSeconds;[Math]::Round( ($_.CPU * 100 / $TotalSec), 2)}};$CPU = #{Name='CPU';Expression={[Math]::Round($_.cpu,2)}}; Get-Process | Select -Property Name, $CPU, $CPUPercent,#{Name='Memory (MB)';Expression={($_.WorkingSet64/1MB)}}, Description | Sort -Property CPU -Descending | Format-Table -AutoSize
$CPUPercent = Get-Process | Select -Property Name, $CPU, $CPUPercent,#{Name='Memory (MB)';Expression={($_.WorkingSet64/1MB)}}, Description | Sort -Property CPU -Descending | Format-Table -AutoSize
foreach($CPUPer in $CPUPercent)
{
$name_1=$CPUPer.Name
$cpu_1=$CPUPer.CPU
$cpu_percent_1=$CPUPer.CPU %
$memory_1=$CPUPer.Memory (MB)
$descr_1=$CPUPer.Description
#$insertquery="
#INSERT INTO [dbo].[ServiceTable]
# ([Name]
# ,[CPU]
# ,[CPU_Perc]
# ,[Memory_MB]
# ,[Description])
# VALUES
# ('$name_1'
# ,'$cpu_1'
# ,'$cpu_percent_1'
# ,'$memory_1'
# ,'$descr_1')
#GO
#"
#Invoke-SQLcmd -ServerInstance 'KILIKOOD-PC\MSSQLSERVER,1433' -query $insertquery -U sa -P test123 -Database Fantasy
}

I think use ' ' for names will solve your problem, check it out
$CPUPer.'CPU %'
$CPUPer.'Memory (MB)'

Related

How does one add output from a cmdlet to an array?

I am trying to determine if specific Windows hotfixes are installed on our Windows servers. I am quite new to PowerShell scripting and this is what I have so far:
$servers = Get-ADComputer -Filter {(OperatingSystem -like "Windows Server 2019*") -and (enabled -ne $false)} -Property *
$result = #()
ForEach ($item in $servers) {
$testhotfix = Get-HotFix -Id KB4534310,KB4534314,KB4534283,KB4534288,KB4534297,KB4534309,KB4534271,KB4534273 -ComputerName $item.Name | `
select $item.Name,$item.CanonicalName,$item.OperatingSystem
$result += $testhotfix
}
$result | Export-Csv -Path C:\Users\user1\Desktop\Servers.csv -NoTypeInformation
The CSV file that is created includes one line with the information I'm looking for, followed by several lines of commas, like so:
Script Output
"SERVER1","somedomain.com/Servers/Non-Prod/New_Server_Staging/SERVER1","Windows Server 2019 Standard"
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
,,
We have several servers with at least one of the hotfixes installed. How do I add each server to the $result array?
Thank you
Generally speaking:
select $item.Name,$item.CanonicalName,$item.OperatingSystem
should be:
select Name, CanonicalName, OperatingSystem
That is, you need to pass the property names (e.g., Name), not the current input object's property values (e.g., $item.Name) to select (the Select-Objectcmdlet).
The net effect is that Select-Object creates custom objects whose properties are (mistakenly) named for the property values and themselves have no value, given that the input objects have no such properties.
This explains the output you saw.
However, the bigger problem is that even that won't work, given that the property names relate to the $item object, not to the objects output by Get-HotFix, which are the ones select operates on.
As it turns out, what you really need is to use the Get-HotFix call as a conditional, so as to only write a CSV row for the computer at hand if at least one of the specified hotfixes is installed:
$hotfixIds = 'KB4534310', 'KB4534314', 'KB4534283', 'KB4534288', 'KB4534297', 'KB4534309', 'KB4534271', 'KB4534273'
if (0 -ne (Get-HotFix -ErrorAction SilentlyContinue -Id $hotfixIds -ComputerName $item.Name).Count) {
$result += $item | select Name, CanonicalName, OperatingSystem
}
Note:
Note how it is now $item (the computer at hand) that is piped to select, to ensure that its properties are extracted (in the form of a custom object with these properties).
You could omit 0 -eq altogether and rely on PowerShell's implicit to-Boolean conversion, where any nonzero number evaluates to $true (see the bottom section of this answer for a summary of all rules.
If instead you want to test for all of the specified hotfixes being installed, replace 0 -ne with $hotfixIds.Count -eq.
-ErrorAction SilentlyContinue silences the errors from computers where none of the specified hotfixes are installed; you could examine the automatic $Error collection afterwards, or use -ErrorVariable err to collect all command-specific errors in variable $err.
Also, your overall command can be greatly streamlined - see the bottom section.
A solution for a different scenario, that may be of interest as well:
If you wanted to combine properties from the Get-HotFix output objects with properties from the $item objects (representing the computer at hand):
The following command:
selects all properties from the Get-HotFix output objects (-Property *)
adds the properties of interest from the current $item, using calculated properties
# Additional 'KB...' values omitted for brevity.
Get-HotFix -Id KB4534310, KB4534314 -ComputerName $item.Name |
Select-Object -Exclude Name -Property *,
#{ n = 'Name'; e = { $item.Name } },
#{ n = 'CanonicalName'; e = { $item.CanonicalName } },
#{ n = 'OperatingSystem'; e = { $item.OperatingSystem } }
Note that -Exclude Name excludes the Name property from the input objects (Get-HotFix output objects that have such a property, but it is empty), so that Name can be added as a property containing the computer name.
As for what you tried:
Aside from the Select-Object property-name problem mentioned above, your major problem was that you expected a pipeline segment as a conditional, which is not how pipelines work:
Get-HotFix ... | select ...
The above simply sends Get-HotFix's output objects to select (Select-Object), which then unconditionally processes them (and, as stated, looks for properties with the given names on these objects).
Now, if Get-HotFix produced no output, then conditional logic applies implicitly: the select command would then simply not be invoked.
Conversely, if Get-HotFix produces multiple outputs, select would be invoked on each.
That is, if we had naively tried to correct your command from:
Get-HotFix ... | select ...
to:
Get-HotFix ... | ForEach-Object { $item | select ... }
you would have potentially created multiple output objects per computer, namely whenever a given computer happens to have more than one among the given hotfixes installed.
A streamlined version of your (corrected) command:
Your command can be streamlined to use a single pipeline only, without the need for aux. variables:
Get-ADComputer -Filter '(OperatingSystem -like "Windows Server 2019*") -and (enabled -ne $false)' -Property * |
ForEach-Object {
if (0 -ne (Get-HotFix -ErrorAction SilentlyContinue -ComputerName $item.Name -Id KB4534310,KB4534314,KB4534283,KB4534288,KB4534297,KB4534309,KB4534271,KB4534273).Count) {
$item | select Name, CanonicalName, OperatingSystem
}
} | Export-Csv -Path C:\Users\user1\Desktop\Servers.csv -NoTypeInformation
Note:
If you end a line with |, you do not need a trailing ` to signal line continuation.
PowerShell [Core] v7.0+ now also allows placing | at the start of the very next line.
A single-quoted string ('...') is used instead of a script block ({ ... }) to pass the -Filter argument, because tt's best to avoid the use of script blocks ({ ... }) as -Filter arguments.
The output custom object instances created with $item | select Name, CanonicalName, OperatingSystem are sent directly to the pipeline.
I would use a PSCustomObject.
$array = foreach($item in $obj)
{
[PSCustomObject]#{
Name = $item.Name
CanonicalName = $item.CanonicalName
OS = $item.OperatingSystem
}
}

"Normalizing" a CSV file

I have a CSV file for help desk calls. The same ticket might have 1,2, or even 5 records based on the number of updates it has. (One field is different, all other fields are identical).
I want to take the mostly-duplicate records and create one record with the differences concatenated into it. Having programmed in the past, but being a newbie to PowerShell, I could use some help.
So, based on a previous question I asked, here's what I have so far. Assuming data like this:
ID, Date, Comment
345, 1/1/16, Moss has reported a fire in the I/T Room
345, 1/1/16, Never mind, he has sent an e-mail about it.
346, 1/2/16, Someone on the 5th floor is complaining about a man under her desk.
347, 2/1/16, Jen says she has broken the Internet.
347, 2/1/16, Douglas is very angry, we need a fix ASAP!
347, 2/1/16, Roy was playing a joke on her. Closing ticket.
I have the following code:
$FileList = Import-Csv "Call List.csv"
$incidents = $FileList | Group ID
foreach($group in $incidents)
{
# What goes here?
}
How do I take the comments from the 2nd, 3rd, etc. line in the group, concatenate it to the comment in the first, and write the file out?
The Group-Object produces an object with Name and Group, Group containing all the items in that group. You can extract them and create a new object using something like this:
$incidents = $FileList | Group-Object ID | % {
New-Object psobject -property #{
ID = $_.Name
Date = $_.Group[0].Date
Comment = ($_.Group | Select -Expandproperty Comment) -Join "`n"
}
}
(not tested as I am currently on a Mac)
I'd first get a list of the unique IDs, for example:
$Ids = $FileList | Select-Object -ExpandProperty Id -Unique
Then I'd look through the list of tickets and build up a "report" for each ID:
foreach($Id in $Ids){
# Get all incident logs for this Id:
$logs = $FileList | ?{$_.Id -eq $Id}
$report = ""
foreach($log in $logs){
$report += $log.Date + ": " + $log.Comment + "; "
}
# Now you can write the text out
$report | Out-File $Outfile -Append
}
Hope that gives you an idea.

How to Parse the Results of CMDlet into Array

I am sure there is an easy answer to this question, but I cannot find it anywhere. I would like to know how to parse the results of Get-Mailbox | select Alias into an array so each time I use the array it does not show the items as "#{Alias=username}".
I have tired this, but it seems to make the values not text:
$arrayname = Get-Mailbox | select Alias
I am sure this question has been asked before, but I cannot find it.
Essentially I would like to get the Alias' from the Get-Mailbox command into an array so that I can use the foreach cmdlet to get specific folder information from a user like so:
>> $aliases = Get-Mailbox | select Alias
>> Foreach ($username in $aliases) {Get-MailboxFolderStatistics -identity $username | select FolderPath | where {$_.FolderPath -like '*Deleted*'} | Export-CSV "C:\users\username\desktop\allusers-deletedfolder-postarchive.csv" -NoTypeInformation}
The cmdlet already produces an array, only that its elements are mailbox objects, not strings. Selecting the Alias property restricts the object properties, but still leaves you with an array of objects (hence the output you observed). You need to expand the property:
$arrayname = Get-Mailbox | select -Expand Alias
or echo it in a loop:
$arrayname = Get-Mailbox | % { $_.Alias }

Unable to extract VirtualNetwork Name using SCVMM powershell modules

Im trying to extract virtual network information for a VM using powershell, i tried using regular expression but for VM's with more than 1 NIC im unable to see output
Below is the output which i need..
PS C:\> get-vm sql.IAN01.Host | select -ExpandProperty virtualnetworkadapters | select virtualnetwork
VirtualNetwork
--------------
VirtualUplink
iSCSI1
iSCSI2
VirtualUplink
But when i try using regular expressions it does not give me an output, Network comes blank
PS C:\> Get-VM sql.IAN01.Host | Select #{Name="VMName";Expression={$_.name}},#{Name="Network
";Expression={#((get-vm $_.name | select -ExpandProperty virtualnetworkadapters).virtualnetwork)}}
VMName Network
------ -------
sql.IADPSQLHST1N01.Hosting
Can anyone please help me out!!
Try this:
Get-VM sql.IAN01.Host | Select-Object #{Name="VMName";Expression={$_.name}},#{Name='VirtualNetwork';e={$_.VirtualNetworkAdapters | Foreach-Object{$_.VirtualNetwork}}}

PowerShell script to list items in collection

I'm new to PowerShell and am trying to query against my SQL server. I get the idea of creating a new-psdrive and then navigating to databases etc and have a line of code as
$dbs = (get-childitem
sqlserver:\sql\SERVER\INSTANCE\databases)
when I pipe the $dbs to a foreach, how would I get results of a collection of the database object? I am trying to read the extendedproperties of my test database.
This single query gives the results I want repeated for each database.
set-location
DRIVENAME:\databases\beagle_test\extendedproperties
get-childitem | select displayname,
value
any help very much appreciated.
I dont have SQL server handy to try this. Let me know the result
Set-Location DRIVENAME:\Databases
Get-ChildItem | % { Get-ChildItem $("$_.Name\extendedproperties") | Select DisplayName, Value }
Try this
Set-Location DRIVENAME:\Databases
Get-ChildItem | foreach-object { if (Test-Path $("$.Name\extendedproperties")) { Get-ChildItem $("$.Name\extendedproperties") | Select DisplayName, Value } }
The second line here is a single statement. What I am doing is to check if Extendedproperties exist and then get child item.
How about:
dir sqlserver:\sql\ServerName\InstanceName\Databases\*\ExtendedProperties\* |
select #{Name="Database";Expression={$_.Parent.Name}}, Name, Value
How about just:
dir SQLSERVER:\SQL\Server\Instance\databases\*\extendedproperties\* | % {select $_.displayname, $_.value}
so, many years later I am looking into my SO stats and see this old question and figure that my powershell skills have grown a little since 2010.
The use-case has long gone but I think what I was trying to achieve is this:
foreach ($db in $SMOServer.databases | Where-Object status -eq 'normal') {
$db.ExtendedProperties | Select-Object #{name = "DBName"; expression = {$db.Name}}, name, value
}
which gives results like this:
DBName Name Value
------ ---- -----
AdventureWorks2014 MS_Description AdventureWorks 2014 Sample OLTP Database
AdventureWorks2016 MS_Description AdventureWorks 2016 Sample OLTP Database

Resources