Enumerating a PSCustomObject - powershell

Does anyone have know of a way to "break" open a hash table source from a custom object. There is no .getenumerrator on a custom object but I have this hashtable: #{0=0.05; 1024=0.050; 51200=0.050; 512000=0.050; 1024000=0.045; 5120000=0.037}. I am pulling this information via the Azure RateCard REST API and need to break it down so I have access to each tier of rates to generate an accurate report of usage cost. Any suggestions? Sample outputs:
MeterId : d23a5753-ff85-4ddf-af28-8cc5cf2d3882
MeterName : Standard IO - Page Blob/Disk (GB)
MeterCategory : Storage
MeterSubCategory : Locally Redundant
Unit : GB
MeterTags : {}
MeterRegion :
MeterRates : #{0=0.05; 1024=0.050; 51200=0.050; 512000=0.050; 1024000=0.045; 5120000=0.037}
EffectiveDate : 2014-02-01T00:00:00Z
IncludedQuantity : 0.0
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
EffectiveDate NoteProperty System.String EffectiveDate=2014-02-01T00:00:00Z
IncludedQuantity NoteProperty System.Decimal IncludedQuantity=0.0
MeterCategory NoteProperty System.String MeterCategory=Storage
MeterId NoteProperty System.String MeterId=d23a5753-ff85-4ddf-af28-8cc5cf2d3882
MeterName NoteProperty System.String MeterName=Standard IO - Page Blob/Disk (GB)
MeterRates NoteProperty System.Management.Automation.PSCustomObject MeterRates=#{0=0.05; 1024=0.050; 51200=0.050; 512000=0.050; 1024000=0.045; 5120000=0.037}
MeterRegion NoteProperty System.String MeterRegion=
MeterSubCategory NoteProperty System.String MeterSubCategory=Locally Redundant
MeterTags NoteProperty System.Object[] MeterTags=System.Object[]
Unit NoteProperty System.String Unit=GB

Not sure what it is you mean by break open but this should give you the keys:
$object.MeterRates.keys
This will give you the values:
$object.MeterRates.keys | % {$object.MeterRates[$_]}
Are you after the total value? I guessing it might be something like this:
($object.MeterRates.keys | % {$object.MeterRates[$_] * $_} | Measure-Object -Sum).Sum

There's probably a better way to do this but my particular version of powershell hacking produced something like this -
$a = "#{0=0.05; 1024=0.050; 51200=0.050; 512000=0.050; 1024000=0.045; 5120000=0.037}"
$b = ConvertFrom-StringData `
-StringData $a.Replace("; ","`n").Replace("#","").Replace("{","").Replace("}","")
This presumes that the entire string is available, replace the semicolons with newlines, ditches the other bits and give it to ConvertFrom-StringData

Found this code on a similar question. Solves my problem:
$js | Get-Member -MemberType NoteProperty).Name

Related

Get-ItemProperty with wildcard; results as array

Given a registry key of
registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey
and text properties called TestString1, TestString2 & NotValid
I can use
Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*"
and I will get back
TestString1 : One
TestString2 : Two
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSChildName : TestKey
PSProvider : Microsoft.PowerShell.Core\Registry
But what I want is an array of just the two properties who's names match the wildcard.
Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*" | Get-Member
produces
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
PSChildName NoteProperty string PSChildName=TestKey
PSParentPath NoteProperty string PSParentPath=Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSPath NoteProperty string PSPath=Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey
PSProvider NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\Registry
TestString1 NoteProperty string TestString1=One
TestString2 NoteProperty string TestString2=Two
which makes me think
Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*" | Where-Object ({$_.Name -like "TestString*"})
should do what I want, but it actually returns nothing. What am I missing here?
EDIT: OK, this is weird. And I guess typical Microsoft "thinking". If I actually have a property called TestString*, which is a perfectly valid name, because Microsoft is never consistent, the code above returns all three, plus the other stuff. But, if I change the -Path to -LiteralPath, then I only get the one -Name. Which is... crazy. I have never seen any documentation saying that -LiteralPath also makes -Name behave like -LiteralName.

Parsing strings before character in Powershell

I want to obtain the environment, project name and location from a string and store it in a variable in Powershell.
The string is in the format of env-project-location. Exampleuat-hrapp-westeurope
How do I filter the string and store the outputs in a variable?
$environment = "uat"
$project = "hrapp"
$location = "westeurope"
You don't need regex for this, assuming the string will always have the same naming convention a simple split would do it:
$environment, $project, $location = 'uat-hrapp-westeurope'.Split('-')
Santiago Squarzon's post got me thinking so I did a little googling and found that you can also use this method if you want a PSCustomObject vs independent variables.
Clear-Host
$Base = "uat-hrapp-westeurope"
$CFSArgs = #{PropertyNames = "Environment", "Project", "Location"
Delimiter = '-'}
$obj = $Base | ConvertFrom-String #CFSArgs
$Obj
Output:
Environment Project Location
----------- ------- --------
uat hrapp westeurope
PS> $obj | gm
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Environment NoteProperty string Environment=uat
Location NoteProperty string Location=westeurope
Project NoteProperty string Project=hrapp

Get all the names of the applications in a site

I am trying to write a powershell script which gets the names of each application in a website in IIS in order to change the app pool associated with it. I am able to get the website, but I don't see a clear way to fetch each of the names?
Eg. I want to loop through them all: Api, Services, etc.. and then use
Set-ItemProperty "IIS:\Sites\RootSite\$loopedValue" -Name 'applicationPool' -Value $NewPool
I'm trying this:
Get-WebApplication -Site 'ABC'
Name Application pool Protocols Physical Path
---- ---------------- --------- -------------
Api ABC http C:\Api
Services ABC http C:\Services
Director ABC http C:\Director
ReportingServer ABC http C:\ReportingServer
But there is no way to get the Name from the members of Get-WebApplication.
Get-WebApplication | Get-Member
TypeName: Microsoft.IIs.PowerShell.Framework.ConfigurationElement#site#application
Name MemberType Definition
---- ---------- ----------
ClearLocalData Method void ClearLocalData()
Copy Method void Copy(Microsoft.IIs.PowerShell.Framework.ConfigurationElement target, bool recurse)
Delete Method void Delete()
Equals Method bool Equals(System.Object obj), bool IEquatable[ConfigurationElement].Equals(Microsoft.IIs.PowerShell.Framework.Conf...
GetAttribute Method Microsoft.IIs.PowerShell.Framework.ConfigurationAttribute GetAttribute(string attributeName)
GetAttributeValue Method System.Object GetAttributeValue(string attributeName)
GetChildElement Method Microsoft.IIs.PowerShell.Framework.ConfigurationElement GetChildElement(string elementName), Microsoft.IIs.PowerShel...
GetCollection Method Microsoft.IIs.PowerShell.Framework.ConfigurationElementCollection GetCollection(string collectionName), Microsoft.II...
GetHashCode Method int GetHashCode()
GetMetadata Method System.Object GetMetadata(string metadataType)
GetParentElement Method Microsoft.IIs.PowerShell.Framework.ConfigurationElement GetParentElement()
GetType Method type GetType()
LoadProperties Method void LoadProperties(System.Collections.Generic.Dictionary[string,System.Object] propCollection)
SetAttributeValue Method void SetAttributeValue(string attributeName, System.Object value)
SetMetadata Method void SetMetadata(string metadataType, System.Object value)
ToPSObject Method psobject ToPSObject(Microsoft.IIs.PowerShell.Framework.ConfigurationElement parent)
ToString Method string ToString()
Update Method void Update(Microsoft.IIs.PowerShell.Framework.ConfigurationElement source), bool Update(psobject data)
UpdateCollection Method bool UpdateCollection(psobject[] arr)
applicationPool NoteProperty string applicationPool=ABC
Collection NoteProperty psobject[] Collection=System.Management.Automation.PSObject[]
ConfigurationPathType NoteProperty ConfigurationPathNodeType ConfigurationPathType=Location
enabledProtocols NoteProperty string enabledProtocols=http
ItemXPath NoteProperty string ItemXPath=/system.applicationHost/sites/site[#name='ABC' and #id='1']/application[#path='/API']
Location NoteProperty string Location=
path NoteProperty string path=/ApiDoc
preloadEnabled NoteProperty bool preloadEnabled=False
PSPath NoteProperty string PSPath=MACHINE/WEBROOT/APPHOST
serviceAutoStartEnabled NoteProperty bool serviceAutoStartEnabled=False
serviceAutoStartProvider NoteProperty string serviceAutoStartProvider=
virtualDirectoryDefaults NoteProperty Microsoft.IIs.PowerShell.Framework.ConfigurationElement#application#virtualDirectoryDefaults virtualDirectoryDefault...
Item ParameterizedProperty System.Object Item(string attributeName) {get;set;}
Attributes Property Microsoft.IIs.PowerShell.Framework.ConfigurationAttributeCollection Attributes {get;}
ChildElements Property Microsoft.IIs.PowerShell.Framework.ConfigurationChildElementCollection ChildElements {get;}
ElementTagName Property string ElementTagName {get;}
Methods Property Microsoft.IIs.PowerShell.Framework.ConfigurationMethodCollection Methods {get;}
Schema Property Microsoft.IIs.PowerShell.Framework.ConfigurationElementSchema Schema {get;}
PhysicalPath ScriptProperty System.Object PhysicalPath {get=$pquery = $this.ItemXPath + "/virtualDirectory[#path='/']/#physicalPath"...
I don't really want to parse a string value from the path or PhysicalPath to do this. Is there another way?
An alternative way I came up with was to join the two results from Get-WebSite and Get-WebApplication
(get-website | select-object #{n='Site'; e={$_.Name}},#{n='Location'; e={$_.PhysicalPath}}) + (get-webapplication | select-object #{n='Site'; e= {$_.GetParentElement().Attributes['name'].value + $_.path }},#{n='Location'; e= {$_.PhysicalPath}})
Output:
Site WebType Location
---- ------- --------
MEDIA WebSite c:\mir\data
DATA WebSite d:\data
Tu***.M*.A***o.Sa****x.N***e WebSite C:\WebSite\Tu***.M*.A***o.Sa****x.N***e
Tu***.***********on.*****ime WebSite C:\WebSite\Tu***.***********on.*****ime
Tu***.**.*****.***********ion WebSite C:\WebSite\Tu***.**.*****.***********ion
Tu***.********.**.****App WebSite C:\WEB\Tu***.********.**.****App
Tu***.********.**.****App/api WebApplication C:\Web\Tu***.********.**.****vate
The following will provide the application names for all sites:
(Get-ChildItem -Path 'IIS:\Sites' -Recurse | Where-Object {$_.NodeType -eq 'application'}).Name
The following will return the application names for Default Web Site:
(Get-ChildItem -Path 'IIS:\Sites\Default Web Site' | Where-Object {$_.NodeType -eq 'application'}).Name

Under what circumstances would one need the information emitted when -NoTypeInformation is *not* passed to ConvertTo-Csv or Export-Csv?

It occurred to me today that, after so many years of habitually passing -NoTypeInformation to Export-Csv/ConvertTo-Csv to prevent that undesirable comment line from being emitted, perhaps Import-Csv/ConvertFrom-Csv would be able to reconstruct objects with their original property types (instead of all of them being String) if only I hadn't suppressed that type information. I gave it a try...
PS> Get-Service | ConvertTo-Csv
...and, having not actually seen in a long time what gets emitted by omitting -NoTypeInformation, was reminded that it only includes the type of the input objects (just the first object, in fact), not the types of the members...
#TYPE System.ServiceProcess.ServiceController
"Name","RequiredServices","CanPauseAndContinue","CanShutdown","CanStop","DisplayName","DependentServices","MachineName","ServiceName","ServicesDependedOn","ServiceHandle","Status","ServiceType","StartType","Site","Container"
...
Comparing the result of serializing with type information and then deserializing...
PS> Get-Service | ConvertTo-Csv | ConvertFrom-Csv | Get-Member
TypeName: CSV:System.ServiceProcess.ServiceController
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
CanPauseAndContinue NoteProperty string CanPauseAndContinue=False
CanShutdown NoteProperty string CanShutdown=False
CanStop NoteProperty string CanStop=True
Container NoteProperty object Container=null
DependentServices NoteProperty string DependentServices=System.ServiceProcess.ServiceController[]
DisplayName NoteProperty string DisplayName=Adobe Acrobat Update Service
MachineName NoteProperty string MachineName=.
Name NoteProperty string Name=AdobeARMservice
RequiredServices NoteProperty string RequiredServices=System.ServiceProcess.ServiceController[]
ServiceHandle NoteProperty string ServiceHandle=
ServiceName NoteProperty string ServiceName=AdobeARMservice
ServicesDependedOn NoteProperty string ServicesDependedOn=System.ServiceProcess.ServiceController[]
ServiceType NoteProperty string ServiceType=Win32OwnProcess
Site NoteProperty string Site=
StartType NoteProperty string StartType=Automatic
Status NoteProperty string Status=Running
...to the result of serializing without type information and then deserializing...
PS> Get-Service | ConvertTo-Csv -NoTypeInformation | ConvertFrom-Csv | Get-Member
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
CanPauseAndContinue NoteProperty string CanPauseAndContinue=False
CanShutdown NoteProperty string CanShutdown=False
CanStop NoteProperty string CanStop=True
Container NoteProperty object Container=null
DependentServices NoteProperty string DependentServices=System.ServiceProcess.ServiceController[]
DisplayName NoteProperty string DisplayName=Adobe Acrobat Update Service
MachineName NoteProperty string MachineName=.
Name NoteProperty string Name=AdobeARMservice
RequiredServices NoteProperty string RequiredServices=System.ServiceProcess.ServiceController[]
ServiceHandle NoteProperty string ServiceHandle=
ServiceName NoteProperty string ServiceName=AdobeARMservice
ServicesDependedOn NoteProperty string ServicesDependedOn=System.ServiceProcess.ServiceController[]
ServiceType NoteProperty string ServiceType=Win32OwnProcess
Site NoteProperty string Site=
StartType NoteProperty string StartType=Automatic
Status NoteProperty string Status=Running
...the only difference is that the TypeName changes from CSV:System.ServiceProcess.ServiceController (the same type specified by the #TYPE comment prefixed with CSV:) to System.Management.Automation.PSCustomObject. All the members are the same, all the properties are of type String, and in both cases you have deserialized objects that do not contain the methods of and are not in any way connected to or proxies of the original objects.
Evidently Microsoft felt that not only could it be desirable to include this type information in the CSV output, but that it should be done by default. Since I can't really ask "Why did they do this?", what I'm wondering is how could this information potentially be useful? Do the *-Csv serialization cmdlets use it for anything other than setting the TypeName of each object? Why would I ever want this type information communicated "in-band" in the CSV output as opposed to just...knowing that this file containing service information came from System.ServiceProcess.ServiceController instances, or even just not caring what the original type was as long as it has the properties I expect?
The only two use cases I can think of are if you receive a CSV file created by an unknown PowerShell script then having the type information can aide in determining what application/library/module was used to produce the data, or if you had a ridiculously general script that attempted to refresh arbitrary input based on the type information, like this...
Import-Csv ... `
| ForEach-Object -Process {
# Original type name of the first record, not necessarily this record!
$firstTypeName = $_.PSObject.TypeNames[0];
if ($firstTypeName -eq 'CSV:System.ServiceProcess.ServiceController')
{
Get-Service ...
}
elseif ('CSV:System.IO.DirectoryInfo', 'CSV:System.IO.FileInfo' -contains $firstTypeName)
{
Get-ChildItem ...
}
elseif ($firstTypeName -eq 'CSV:Microsoft.ActiveDirectory.Management.ADObject')
{
Get-ADObject ...
}
...
}
...but those aren't very compelling examples, especially considering that, as I noted, this type information was deemed so important that it is included by default. Are there other use cases I'm not thinking of? Or is this simply a case of "It's better (and cheap) to include it and not need it than to need it and not include it"?
Related: PowerShell GitHub issue with discussion about making -NoTypeInformation the default in a then-future version (6.0, according the cmdlet documentation), as well as an apparent consensus that there's no point in ever omitting -NoTypeInformation.
If you have a thing which understands the header and also knows how to construct an other thing of that type, then that first thing could conceivably create one or more those other things from the string representation. I'm not saying it's useful but I am saying that is a potential use if a .csv might be usable where a file of another type might not. I may or may not have actually done this for reasons similar to what I mention here in answer to your question.

Using a Powershell noteproperty as a text string in a variable

I've used Invoke-Restmethod to download some data, which Powershell stores in a PSCustomObject, in a property called data.
I need to use the value of one of the items in the returned data as a variable for another command. I have managed to select-object -expand my way down to the following output from Get-Member:
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
id NoteProperty System.Int32 id=999
What I need to do is grab the value of the ID noteproperty - 999 - and pass that as part of a string to a new variable, eg:
$newVar = "sometext" + 999 + "moretext"
No amount of select-string or out-string etc is helping. Scripting is not exactly my strong point so I'm not sure I'm even articulating what I want properly - apologies if this is the case!
Any assistance much appreciated
I'm not sure exactly what your code and looks like, so I created the following static approximation from the description:
$data = New-Object PSCustomObject
$data | Add-Member -Type NoteProperty -Name Id -Value 999
$restResponse = New-Object PSCustomObject
$restResponse | Add-Member -Type NoteProperty -Name data -Value $data
Please clarify if this is not a match. You can get the Id value as follows
$restResponse.data.Id
Assign it to another variable
$newVar = "sometext" + $restResponse.data.Id + "moretext"
$newVar
And if your REST response is a collection of data objects, iterate through them
$restResponse.data | Foreach-Object { "sometext" + $_.Id + "moretext" }
I would go for for using $output | select *,#{n='test';e={[string]$_.test}} -exclude properties test
if the exclude is not active it will complain about it already exists. Mostly I use the select expression to manipulate data realtime instead of psCustomObject for such simple task