powershell pull variable from inf file - powershell

$OEM = "N/A"
$data = (get-content C:\Windows\INF\OEM27.inf | select-string "10.18.10.4358")
if ($data -eq "DriverVer=12/21/2015,10.18.10.4358"){
$OEM = $true}
else {$OEM = $false}
echo $data
echo $OEM
So I'm trying to test this small code out before adding it to my larger script. However $OEM keeps coming up a False even though $data comes back as DriverVer=12/21/2015,10.18.10.4358. Not sure what I'm over looking but it is pretty late at night. Any help would be appreciated. ^^"

The object returned by Select-String isn't a string. It is a MatchInfo:
C:\> $data | Get-Member
TypeName: Microsoft.PowerShell.Commands.MatchInfo
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
RelativePath Method string RelativePath(string directory)
ToString Method string ToString(), string ToString(string directory)
Context Property Microsoft.PowerShell.Commands.MatchInfoContext Context {get;set;}
Filename Property string Filename {get;}
IgnoreCase Property bool IgnoreCase {get;set;}
Line Property string Line {get;set;}
LineNumber Property int LineNumber {get;set;}
Matches Property System.Text.RegularExpressions.Match[] Matches {get;set;}
Path Property string Path {get;set;}
Pattern Property string Pattern {get;set;}
You can get to the line it matches on with the Line property. So change your code to this:
if ($data.Line -eq "DriverVer=12/21/2015,10.18.10.4358")
However, I don't think that is very robust code because INI files can have spaces around the "=". This would be better:
if ($data.Line -match "DriverVer\s*=\s*12/21/2015,10.18.10.4358")
I think your code is a bit over complicated. You could replace the whole thing with this:
$OEM = [bool](Select-String "DriverVer\s*=\s*12/21/2015,10.18.10.4358" C:\Windows\INF\OEM27.inf)

Related

Power Shell Output filter

I'm using the comand Get-AzresourceGroup. The ouput of that command is information about ResourID, Tags, Resource group name etc. of all resource groups in Azure. I want to store in a variable all the names of the resource groups, I do not need the other information. Is there a way I can do that?
Thank you!
Comand Output
From the Get-AzResourceGroup documentation, you can simply reference only the Resource Group Name :
$groups = (Get-AzResourceGroup).ResourceGroupName
Or using the CLI, and extracting from the JSON:
$group = az group list | ConvertFrom-Json
$group | Select-Object -Property Name
Try piping the output from Get-AzResourceGroup to Select-Object and use the -Property parameter to specify the property/properties to select.
$rgs = Get-AzResourceGroup | Select-Object -Property ResourceGroupName
Your will results should look something like this.
$rgs
ResourceGroupName
-----------------
ddo-06212021-1
ddo-06212021-2
ddo-06212021-3
cloud-shell-storage-eastus
If you're unsure what properties are available to select from the results of Get-AzResourceGroup, you can first pipe the output to Get-Member, and view the available properties.
Get-AzResourceGroup | Get-Member
TypeName: Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceGroup
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Location Property string Location {get;set;}
ManagedBy Property string ManagedBy {get;set;}
ProvisioningState Property string ProvisioningState {get;set;}
ResourceGroupName Property string ResourceGroupName {get;set;}
ResourceId Property string ResourceId {get;set;}
Tags Property hashtable Tags {get;set;}
TagsTable Property string TagsTable {get;}
Links
Select-Object - learn.microsoft.com
Get-Member - learn.microsoft.com

Powershell Get-EventLog find event with the matching string in its message

I need to look through eventLog security ID 4648, and find the last time the user connected to the machine.
Currently this is my code:
$Values = invoke-command -ComputerName $ComputerName {Get-EventLog -LogName Security -InstanceID 4648 | Select-Object -ExpandProperty Message| ForEach-Object {if($_.Log -match "$String2"){
$_
Break }}}
$Values
The aim was to go through each log until a log where the message has the previously defined username is found, and then stop going through EventLog and return that log.
This is working well, except its not matching the correct log with the specified string.
Is there a way to improve how the matching works? So it actually finds the correct log with the specified user?
# Fill in the regex for the userName
$userName = "userName"
$Values = #(invoke-command -ComputerName $ComputerName {
Get-EventLog -LogName Security -InstanceID 4648 | Where-Object { $_.message -match $Using:userName } | Select-Object -First 1)
}
Your above sample won't work since message is of type string, therefore it doesn't have a Log property. Since we want $userName to be avaiable for read access on the remote machine we can use the $Using: syntax. To break the pipeline "iteration" I'm using Select-Object -First 1 which will return the first object passing the Where-Objectclause.
Resulting from that $Values points to a collection of (deserialized) objects (using the #() operator) of type:
TypeName: System.Diagnostics.EventLogEntry#Security/Microsoft-Windows-Security-Auditing/4648
Which means you can change the -First parameter to e.g. 10 and sort the result on the client machine:
$Values | sort TimeGenerated -Descending
If you want to know which properties are available you can use:
> $Values | gm
TypeName: System.Diagnostics.EventLogEntry#Security/Microsoft-Windows-Security-Auditing/4648
Name MemberType Definition
---- ---------- ----------
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Diagnostics.EventLogEntry otherEntry), bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetObjectData Method void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
ToString Method string ToString()
Category Property string Category {get;}
CategoryNumber Property int16 CategoryNumber {get;}
Container Property System.ComponentModel.IContainer Container {get;}
Data Property byte[] Data {get;}
EntryType Property System.Diagnostics.EventLogEntryType EntryType {get;}
Index Property int Index {get;}
InstanceId Property long InstanceId {get;}
MachineName Property string MachineName {get;}
Message Property string Message {get;}
ReplacementStrings Property string[] ReplacementStrings {get;}
Site Property System.ComponentModel.ISite Site {get;set;}
Source Property string Source {get;}
TimeGenerated Property datetime TimeGenerated {get;}
TimeWritten Property datetime TimeWritten {get;}
UserName Property string UserName {get;}
EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}
Hope that helps.

How can I find the 'sub properties' of an object in powershell?

I guess I just don't know the proper name of whatever I'm looking for, but this was probably asked a thousand times before.
I started PowerShell not long ago, and I'm struggling to understand where I can find the 'sub properties'(if you can call it those) of an object.
For instance, I was using the VMware PowerCLI, and was tried to figure out how I can find the IP address of a VM.
So for example, I was using the Get-VM command, and when I piped it into get member, I got the following:
PS C:\Users\eitan.rapaport> get-vm "*VRA*" | gm
TypeName: VMware.VimAutomation.ViCore.Impl.V1.VM.UniversalVirtualMachineImpl
Name MemberType Definition
---- ---------- ----------
ConvertToVersion Method T VersionedObjectInterop.ConvertToVersion[T]()
Equals Method bool Equals(System.Object obj)
GetClient Method VMware.VimAutomation.ViCore.Interop.V1.VIAutomation VIObjectCoreInterop.GetClient()
GetConnectionParameters Method VMware.VimAutomation.ViCore.Interop.V1.VM.RemoteConsoleVMParams RemoteConsoleVMIn..
GetHashCode Method int GetHashCode()
GetType Method type GetType()
IsConvertableTo Method bool VersionedObjectInterop.IsConvertableTo(type type)
LockUpdates Method void ExtensionData.LockUpdates()
ObtainExportLease Method VMware.Vim.ManagedObjectReference ObtainExportLease.ObtainExportLease()
ToString Method string ToString()
UnlockUpdates Method void ExtensionData.UnlockUpdates()
CoresPerSocket Property int CoresPerSocket {get;}
CustomFields Property System.Collections.Generic.IDictionary[string,string] CustomFields {get;}
DatastoreIdList Property string[] DatastoreIdList {get;}
DrsAutomationLevel Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.DrsAutomationLevel] ..
ExtensionData Property System.Object ExtensionData {get;}
Folder Property VMware.VimAutomation.ViCore.Types.V1.Inventory.Folder Folder {get;}
FolderId Property string FolderId {get;}
Guest Property VMware.VimAutomation.ViCore.Types.V1.VM.Guest.VMGuest Guest {get;}
GuestId Property string GuestId {get;}
HAIsolationResponse Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.HAIsolationResponse]..
HardwareVersion Property string HardwareVersion {get;}
HARestartPriority Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.HARestartPriority] H..
Id Property string Id {get;}
MemoryGB Property decimal MemoryGB {get;}
MemoryMB Property decimal MemoryMB {get;}
Name Property string Name {get;}
Notes Property string Notes {get;}
NumCpu Property int NumCpu {get;}
PersistentId Property string PersistentId {get;}
PowerState Property VMware.VimAutomation.ViCore.Types.V1.Inventory.PowerState PowerState {get;}
ProvisionedSpaceGB Property decimal ProvisionedSpaceGB {get;}
ResourcePool Property VMware.VimAutomation.ViCore.Types.V1.Inventory.ResourcePool ResourcePool {get;}
ResourcePoolId Property string ResourcePoolId {get;}
Uid Property string Uid {get;}
UsedSpaceGB Property decimal UsedSpaceGB {get;}
VApp Property VMware.VimAutomation.ViCore.Types.V1.Inventory.VApp VApp {get;}
Version Property VMware.VimAutomation.ViCore.Types.V1.VM.VMVersion Version {get;}
VMHost Property VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost VMHost {get;}
VMHostId Property string VMHostId {get;}
VMResourceConfiguration Property VMware.VimAutomation.ViCore.Types.V1.VM.VMResourceConfiguration VMResourceConfigu..
VMSwapfilePolicy Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.VMSwapfilePolicy] VMSwapfile..
As you can see, nothing mentions anything about IP.
I was researching this online, and have found that I should run the following command:
Get-VM | Select Name, #{N="IP Address";E={#($_.guest.IPAddress[0])}}
Which leads me to my question. How can I find the properties under a certain member/property of a command? How could I research the 'sub properties' of 'guest' in that example?
Okay, found it.
In that instance it would be get-vm "*VRA*" | select -ExpandProperty guest | gm
I've been dealing with this for the last two days, so I figured I'd share my solution:
First, I'm saving the VM object to a variable to make it easy to access without searching every time.
$vm = Get-vm -Name steve
To get all the properties of the VM Object
$vm | Select-Object *
If you just want to get the Name you can access it like this:
$vm.Name
If you want to get the Properties of the Guest Object (which is a property of the VM object):
$vm.Guest | Select-Object *
You can access the Properties of the Guest Object through the VM Object like this:
$vm.Guest.VmName
Want the IP addresses of the guest?
$vmip = $vm.Guest.IPAddress
And, because this took me a while to figure out, if that returns ipv4 and ipv6, and you want to filter out the ipv6:
$vmip = $vm.Guest.IPAddress | ?{$_ -notmatch ':'}
Another method of introspection in PowerShell is to just get the class name and then look it up in the API.
PS C:\> $Files = Get-ChildItem *.* -File
PS C:\> $Files[0].GetType().FullName
System.IO.FileInfo
You can then search for that class with either C# or PowerShell to find the API listing.
You can do a similar thing with the VMWare PowerCLI doc. The "all types" list on the left is a list of all the classes used by the module.

Powershell Match Statement from list of Files

I am searching through a directory looking for files that only contain the number 0.
I have used the code:
$fileList = Select-String -Path c:\cnt\*.txt -pattern "0"
And it outputs a list, such as:
C:\cnt\itm123.txt:1:0
c:\cnt\itm1234.txt:1:0
c:\cnt\itm123456.txt:1:0
I need to only extract the itm### but the total numbers in the filename can range from 3-6.
Using the example above I need a list that looks like:
itm123
itm1234
itm123456
Once I get that I will run each through a SQL query, but I am not worried about that part.
The Select-String cmdlet returns a list of Microsoft.PowerShell.Commands.MatchInfo objects. If you call the Get-Member cmdlet with the parameter -MemberType Properties you will get a list of all exposed properties:
Name MemberType Definition
---- ---------- ----------
Context Property Microsoft.PowerShell.Commands.MatchInfoContext Context {get;set;}
Filename Property string Filename {get;}
IgnoreCase Property bool IgnoreCase {get;set;}
Line Property string Line {get;set;}
LineNumber Property int LineNumber {get;set;}
Matches Property System.Text.RegularExpressions.Match[] Matches {get;set;}
Path Property string Path {get;set;}
Pattern Property string Pattern {get;set;}
In this case, you are looking for the Filename property. So if you execute
Select-String -Path c:\cnt\*.txt -pattern "0" | select FileName
you will get all filenames:
itm123.txt
itm1234.txt
itm123456.txt
Now all you have to do is to remove the file extension which can be done using the .NET method GetFileNameWithoutExtension:
Select-String -Path c:\cnt\*.txt -pattern "0" |
ForEach-Object { [io.path]::GetFileNameWithoutExtension($_.FileName)}
Output:
itm123
itm1234
itm123456

powershell missing member methods in array

I have (yet another) powershell query. I have an array in powershell which i need to use the remove() and split commands on.
Normally you set an array (or variable) and the above methods exist. On the below $csv2 array both methods are missing, i have checked using the get-member cmd.
How can i go about using remove to get rid of lines with nan. Also how do i split the columns into two different variables. at the moment each element of the array displays one line, for each line i need to convert it into two variables, one for each column.
timestamp Utilization
--------- -----------
1276505880 2.0763250000e+00
1276505890 1.7487730000e+00
1276505900 1.6906890000e+00
1276505910 1.7972880000e+00
1276505920 1.8141900000e+00
1276505930 nan
1276505940 nan
1276505950 0.0000000000e+00
$SystemStats = (Get-F5.iControl).SystemStatistics
$report = "c:\snmp\data" + $gObj + ".csv"
### Allocate a new Query Object and add the inputs needed
$Query = New-Object -TypeName iControl.SystemStatisticsPerformanceStatisticQuery
$Query.object_name = $i
$Query.start_time = $startTime
$Query.end_time = 0
$Query.interval = $interval
$Query.maximum_rows = 0
### Make method call passing in an array of size one with the specified query
$ReportData = $SystemStats.get_performance_graph_csv_statistics( (,$Query) )
### Allocate a new encoder and turn the byte array into a string
$ASCII = New-Object -TypeName System.Text.ASCIIEncoding
$csvdata = $ASCII.GetString($ReportData[0].statistic_data)
$csv2 = convertFrom-CSV $csvdata
$csv2
There is no Remove or Split method on .NET's Array type, or added by the PowerShell wrapper around an Array instance. This is quite easy to show:
PS[64bit] E:\> $a = 1,2,3,4,5
PS[64bit] E:\> $a.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS[64bit] E:\> Get-Member -InputObject $a
TypeName: System.Object[]
Name MemberType Definition
---- ---------- ----------
Count AliasProperty Count = Length
Address Method System.Object&, mscorlib, Version=2.0.0.0, Culture=neutral, PublicK...
Clone Method System.Object Clone()
CopyTo Method System.Void CopyTo(array array, int index), System.Void CopyTo(arra...
Equals Method bool Equals(System.Object obj)
Get Method System.Object Get(int )
GetEnumerator Method System.Collections.IEnumerator GetEnumerator()
GetHashCode Method int GetHashCode()
GetLength Method int GetLength(int dimension)
GetLongLength Method long GetLongLength(int dimension)
GetLowerBound Method int GetLowerBound(int dimension)
GetType Method type GetType()
GetUpperBound Method int GetUpperBound(int dimension)
GetValue Method System.Object GetValue(Params int[] indices), System.Object GetValu...
Initialize Method System.Void Initialize()
Set Method System.Void Set(int , System.Object )
SetValue Method System.Void SetValue(System.Object value, int index), System.Void S...
ToString Method string ToString()
IsFixedSize Property System.Boolean IsFixedSize {get;}
IsReadOnly Property System.Boolean IsReadOnly {get;}
IsSynchronized Property System.Boolean IsSynchronized {get;}
Length Property System.Int32 Length {get;}
LongLength Property System.Int64 LongLength {get;}
Rank Property System.Int32 Rank {get;}
Arrays in .NET, and PowerShell, are fixed size. To remove an element you need to copy all but the element to be removed, in PSH this can be done with Where-Object:
$newArray = $oldArray | Where-Object {some-condition-on-$_}
Similarly Select-Object with -First and -Skip parameters can be used to select elements before or after (resp3ectively) an index.
NB System.Array does implement System.Collections.ILst but the explicit implementation of IList.Remove just throws a NotImplementedException.