I have an array $array with many elements, an example looks like this:
ProfileID : 100
UID : 17
Name : SharePoint
Description : SharePoint Server Description
Now I am trying to filter by Name property, string to match is:
$string
SharePoint Policy Assignment
I have tried:
$array | Where-Object {$_.Name -like "$string"}
no match
$array | Where-Object {$_.Name -like "$string*"}
no match
$array | Where-Object {$_.Name -match "$string"}
no match
Is this possible using PowerShell? What am I missing?
The -like operator in PowerShell is used for a wildcard match, so you need to use the wildcard character, the asterisk, *.
Imagine this scenario, where I'm trying to match a particular Windows Service.
$svcs = Get-Service | Select-Object -first 15
C:\temp\blog> $svcs
Status Name DisplayName
------ ---- -----------
Stopped AJRouter AllJoyn Router Service
Stopped ALG Application Layer Gateway Service
Running AMD External Ev... AMD External Events Utility
Stopped AppIDSvc Application Identity
Running Appinfo Application Information
Stopped AppMgmt Application Management
Stopped AppReadiness App Readiness
Stopped AppVClient Microsoft App-V Client
Stopped AppXSvc AppX Deployment Service (AppXSVC)
Stopped aspnet_state ASP.NET State Service
Stopped AssignedAccessM... AssignedAccessManager Service
Running AsSysCtrlService ASUS System Control Service
Running AudioEndpointBu... Windows Audio Endpoint Builder
Running Audiosrv Windows Audio
Running AUEPLauncher AMD User Experience Program Launcher
To use the -Like operator to get a match, I have to provide a Wildcard Character, like this.
$svcs | Where-Object Name -like App*
Status Name DisplayName
------ ---- -----------
Stopped AppIDSvc Application Identity
Running Appinfo Application Information
Stopped AppMgmt Application Management
Stopped AppReadiness App Readiness
Stopped AppVClient Microsoft App-V Client
Stopped AppXSvc AppX Deployment Service (AppXSVC)
Try your operation using a WildCard, and I bet it will work :)
One other thing I noted, your $string is equal to SharePoint Policy Assignment, but the column you're comparing on of .Name is just SharePoint.
To complement FoxDeploy's helpful answer:
With collections that are already are in memory or easily fit, you can use member-access enumeration for a more convenient syntax that also results in much faster execution:
#($array.Name) -like $string # returns sub-array of matching elements
-like, when given an array as the LHS, acts as a filter: only those array elements that match the wildcard expression on the RHS are returned (also as an array).
Note the need for #(...) to ensure that $array.Name is an array, because a single-element array would result in the .Name property getting returned as a scalar (a single string), in which case -like would return a Boolean ($true or $false) rather than acting as a filter.
Also note that many PowerShell cmdlets directly support wildcard expressions as parameter values:
Taking Get-Service as an example, its (implied) -Name parameter supports wildcards:
Get-Service *router* # returns all services whose Name contains "router"
To determine a given cmdlet parameter's wildcard support:
PS> Get-Help Get-Service -Parameter Name
-Name <String[]>
Specifies the service names of services to be retrieved. Wildcards are permitted. By default, this cmdlet gets all of the services on the computer.
Required? false
Position? 1
Default value None
Accept pipeline input? True (ByPropertyName, ByValue)
Accept wildcard characters? false
It should be the Accept wildcard characters? value being true that indicates support for wildcard expressions, however, this is unfortunately not reliable, so also check the parameter description; here, the descriptin part Wildcards are permitted provides the information.
GitHub issue #4716 describes the problem and asks to make the programmatic discoverability of wildcard support reliable.
Related
My colleague used the below powershell query to retrieve log data for past 4 days excluding today which matches operations of the resources and collects features such as EventTimeStamp, Caller, SubscriptionId etc.
Get-AzureRmLog -StartTime (Get-Date).AddDays(-4) -EndTime (Get-Date).AddDays(-1) | Where-Object {$_.OperationName.LocalizedValue -match "Start|Stop|Restart|Create|Update|Delete"} |
Select-Object EventTimeStamp, Caller, SubscriptionId, #{name="Operation"; Expression = {$_.operationname.LocalizedValue}},
I am a newbie to azure and want to generate a report where I can also fetch the 'Tags' name & value against a resource for past 90 days in this report. What will be the powershell query for this? Can I also use python to query this data? I tried searching the documentation and was unable to dig into it, so if anybody could redirect me to the right place it will be helpful.
First of all, you should know that not all azure resources can specify tags, so you should consider this in your code. Please refer to Tag support for Azure resources to check which azure resource supports tags.
For powershell query, I suggest using the new azure powershell az module instead of the old azureRM module.
Here is a simple powershell code with az module. And for testing purpose, I just introduce how to fetch and add tags to the output. Please feel free to change it as per your requirement.
#for testing purpose, I just get the azure activity logs from a specified resource group
$mylogs = Get-AzLog -ResourceGroupName "a resource group name"
foreach($log in $mylogs)
{
if(($log.Properties.Content.Values -ne $null))
{
#the tags is contains in the Properties of the log entry.
$s = $log.Properties.Content.Values -as [string]
if($s.startswith("{"))
{
$log | Select-Object EventTimeStamp, Caller, SubscriptionId,#{name="Operation"; Expression = {$_.operationname.LocalizedValue}}, #{name="tags"; Expression = {($s | ConvertFrom-Json).tags}}
}
#if it does not contains tags.
else
{
$log | Select-Object EventTimeStamp, Caller, SubscriptionId,#{name="Operation"; Expression = {$_.operationname.LocalizedValue}}, #{name="tags"; Expression = {""}}
}
}
#if it does not contains tags.
else
{
$log | Select-Object EventTimeStamp, Caller, SubscriptionId,#{name="Operation"; Expression = {$_.operationname.LocalizedValue}}, #{name="tags"; Expression = {""}}
}
Write-Output "************************"
}
The test result:
For python, you can take a look at this github issue which introduces how to fetch logs from azure activity logs, but you need do some research on how to add tags to the output.
Hope it helps.
I have almost 20 resources in azure, 4 of them have been given Tags #
{"Office1work"="work"}
{"Office2practice"="Practice"}
{"Office3practice"="Practice"}
{"Office4practice"="Practice"}
Now I want to get the resources whose Tag names start with the keyword "Office".
I know to get a resource by a TagName,for example "hello", I simply use the following command,
get-azureRmResource -TagName "Hello"
How can I use the -Tagname property of get-azurermresource to give me all resources whose tags are starting with the keyword "Office" ?
Or is there any other good method to get all resources whose Tags start with a particular string?
Thanks :)
You can use this code snippet:
$resources = Get-AzureRmResources
$resources.foreach{ if ($PSItem.tags.keys -match '^Office') { $PSItem } }
First you get all the resources in the subscription, then you filter out all the resource whose tags do not match the 'Office' "expression".
as #LotPings points out, it would probably make more sense to filter without saving to a temporary variable:
$resources = Get-AzureRmResources|Where-Object {$_.tags.keys -match "^Office"}
Also, I didnt notice you were asking for a starts with filter, so you should use ^Office as a more strict filter (if you need to).
Is there a way to set some sort of configuration on the cluster to remove service fabric application type versions? Like only keep the last 5 versions or something?
For example i have CI/CD deploying new versions of a service fabric app to our cluster, it leaves a bunch of application version types in the cluster. Is there a way to automatically unprovision them over time or only keep a certain number of versions?
There are two options that cross my mind -
Specify UnregisterUnusedApplicationVersionsAfterUpgrade = $true when you execute Deploy-FabricApplication.ps1. This parameter indicates whether to unregister any unused application versions that exist after an upgrade is finished.
Add custom script into your release defintion, deployment script or whereever you want that will resolve all the deployed app types and unprovision those ones that you think are obsolete. Here is the command that
you will need to use - Unregister-ServiceFabricApplicationType. Here is some example of the script that unregisters all the app types except running ones -
#resolve all app types
$appTypes = Get-ServiceFabricApplicationType
foreach($appType in $appTypes)
{
#try to find the match with any of installed applications
$match = Get-ServiceFabricApplication -ApplicationTypeName $appType.ApplicationTypeName | Where-Object {$_.ApplicationTypeVersion -eq $appType.ApplicationTypeVersion}
if(!$match)
{
Write-Host "Deleting $($appType.ApplicationTypeName) $($appType.ApplicationTypeVersion)"
Unregister-ServiceFabricApplicationType -ApplicationTypeName $appType.ApplicationTypeName -ApplicationTypeVersion $appType.ApplicationTypeVersion -Force -Confirm
}
}
You can set CleanupUnusedApplicationTypes to true in the Management section of cluster settings to enable automatic cleanup. From the docs:
This configuration if enabled, allows to automatically unregister unused application type versions skipping the latest three unused versions, thereby trimming the disk space occupied by image store. The automatic cleanup will be triggered at the end of successful provision for that specific app type and also runs periodically once a day for all the application types. Number of unused versions to skip is configurable using parameter "MaxUnusedAppTypeVersionsToKeep".
I believe this requires at least Service Fabric 6.5.
I expanded on Kiyrl's answer keeping the currently deployed version + n history'
#resolve all app types
$appTypes = Get-ServiceFabricApplicationType
$deployedAppArray = #()
foreach($appType in $appTypes){
#try to find the match with any of installed applications
$match = Get-ServiceFabricApplication -ApplicationTypeName $appType.ApplicationTypeName | Where-Object {$_.ApplicationTypeVersion -eq $appType.ApplicationTypeVersion}
if(!$match)
{
$oldApp = new-object psobject -property #{
ApplicationTypeName = $appType.ApplicationTypeName
ApplicationTypeVersion = $appType.ApplicationTypeVersion
}
$deployedAppArray += $oldApp
}
}
$countToKeep = 2 # keeps this many in addition + currently deployed
$uniqueAppTypes = $deployedAppArray | Group-Object "ApplicationTypeName" | Where-Object { $_.Count -gt $countToKeep } | Select-Object -ExpandProperty Name
foreach($appType in $uniqueAppTypes){
$versionsToRemove = $deployedAppArray | Where-Object {$_.ApplicationTypeName -eq $appType}
$toRemoveCount = $versionsToRemove.Length - $countToKeep
$versionsToRemove = $versionsToRemove | Select-Object -First $toRemoveCount
foreach($appToRemove in $versionsToRemove){
Write-Host "Removing $($appToRemove.ApplicationTypeName) $($appToRemove.ApplicationTypeVersion)"
Unregister-ServiceFabricApplicationType -ApplicationTypeName $appToRemove.ApplicationTypeName -ApplicationTypeVersion $appToRemove.ApplicationTypeVersion -Force
}
}
I would like to filter for all LDAP objects where the CN does not equal the sAMAccountName. Therefore I wrote the following query, which unfortunately neither works nor seems to be RFC compliant:
(!(cn=sAMAccountName))
Does anybody know how to acheive the desired functionality?
Best regards
Thomas
LDAP filters do not allow using value of another attribute for filter comparison. You have to fetch the entry and compare both values.
(!(cn=sAMAccountName)) is "RFC compliant", because the right-hand side of the assertion is taken to be a value of the cn attribute.
Using this filter will result in all entries being returned in a search response where value of the cn attribute is present, and the matching rule for cn returns false for the case-insensitive value samaccountname (assuming the cn attribute matching rule has not been changed from the published standard). The results will be subject to:
server time limit
server size limit
server access controls
Perhaps you meant to use
cn=value-of-samaccount-name
If you're in a Windows environment, you can use PowerShell Expression Language for this.
Get-ADUser -Filter * -Server my.domain.name -Properties CN |
Where-Object {$_.CN -ne $_.sAMAccountName}
This is a fairly expensive query because it returns every single user object for PowerShell to do processing on, but it does work.
I need to retrieve the details of all deployed SharePoint solutions, as are displayed in the Central Administration > Operations > Solution Management (AKA the Solution Store), using a PowerShell script (v2.0). Can anyone offer any guidance on how to retrieve this information from the SharePoint solution store via the SharePoint API?
Thanks, MagicAndi.
This is actually pretty easy to do. You conect to the SP Farm and just request get_Solutions.
Here is an example:
# Connect to the Farm
$SPfarm = [Microsoft.SharePoint.Administration.SPFarm]::get_Local()
# What Solution are we looking for?
$solution = "sharepointlearningkit.wsp";
# Get the solutions
$currentSolution = $SPfarm.get_Solutions() | Where-Object { $_.DisplayName -eq $solution; }
$currentSolution;
Based on Mitchell's answer, I have used:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
function Get-LocalSPFarm()
{
return [Microsoft.SharePoint.Administration.SPFarm]::Local
}
function List-Solutions()
{
$farm = Get-LocalSPFarm
foreach ($solution in $farm.Solutions)
{
Write-Host($solution.DisplayName)
# Get-Member -InputObject $solution -MemberType property
}
}
All credit to Mitchell!
You can call stsadm.exe -o enumsolutions from your powershell script. It returns XML data which you can easily convert to [xml] data type and see whatever you need from that.
(stsadm lives in c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\bin)
The output consists of statements similar to this
<Solution Name="yoursolution.wsp">
<Id>ab693dcd-6483-45ad-abba-9c996c67b6e0</Id>
<File>yoursolution.wsp</File>
<Deployed>TRUE</Deployed>
<WebApplicationSpecific>TRUE</WebApplicationSpecific>
<ContainsGlobalAssembly>TRUE</ContainsGlobalAssembly>
<ContainsCodeAccessSecurityPolicy>FALSE</ContainsCodeAccessSecurityPolicy>
<Deployment WebApplication="http://devserver/" />
<LastOperationResult>DeploymentSucceeded</LastOperationResult>
<LastOperationTime>10/26/2009 9:06 AM</LastOperationTime>
</Solution>
Here are three powershell cmdlets I use to pull back the solution information. Mine are simple compared to the ones above but I thought I would submit them anyway :)
In SP2010 Management Shell
To list all the solutions. Returns solution name, id and deployed status
Get-spsolutions
To list all the properties of a particular solution
get-spsolution -identity | select *
List all solutions, properties and output to a file to read :)
get-spsolution | select * | out-file c:\solutions.txt