I have this code that the truth looks very tangled and I would like to make it more beautiful in sight
(Get-AzResource | Where {($_.tags.tag1-eq $null) -or ($_.tags.tag2-eq $null) -or ($_.tags.tag3-eq $null) -or ($_.tags.tag4-eq $null) -or ($_.tags.tag5-eq "") -or ($_.tags.tag6-eq "") -or ($_.tags.tag7-eq "")}
This code fulfills the function of finding resources that do not have certain tags and that are empty, but the problem is that I leave an "-or" can I make it more beautiful in some way?
Use the -contains operator:
Get-AzResource | Where-Object {
($_.tags.tag1, $_.tags.tag2, $_.tags.tag3, $_.tags.tag4 -contains $null) -or
($_.tags.tag5, $_.tags.tag6, $_.tags.tag7 -contains '')
}
Note: The (...) around the -contains operations aren't strictly necessary, given the relative operator precedence of -contains and -or.
Related
Tried to find a list of appools in IIS starting with a common name "as" once found I would like to enable to only those 32bits to true
So far got this but it's not working, any given help will be very much appreaciated
import-module WebAdministration
$enable32bit="true"
$results = Get-IISAppPool | where {$_.Name -like "AS*"}
foreach ($item in $results) {
Set-ItemProperty IIS:\AppPools\$item -Name "enable32BitAppOnWin64" -Value $enable32bit
}
Possibly just this:
Set-ItemProperty IIS:\AppPools\AS* -name "enable32BitAppOnWin64" -Value "true"
i'm trying to use Powershell to query my Storage Accounts by using name filter
I have tried these commands (and their variants) but have not still managed to get this working.
Get-AzStorageAccount | where -FilterScript {($_.ResourceType -eq "storageAccounts") -and ($_.StorageAccountName -contains "Prod") }
Get-AzResource -ResourceType Microsoft.Storage/storageAccounts | Get-AzResource -Name Prod* | ft
Any tips because I'm a bit lost. My goal would be that command / script would print out e.g all Storage Accounts which contains Prod in their name.
You can use Where-Object and -match to filter here:
Get-AzStorageAccount | Where-Object {$_.StorageAccountName -match 'prod'}
Or using -like:
Get-AzStorageAccount | Where-Object {$_.StorageAccountName -like '*prod*'}
If you really want to use Get-AzResource, then you need to filter by the Microsoft.Storage/storageAccounts resource type:
Get-AzResource -ResourceType "Microsoft.Storage/storageAccounts" | Where-Object {$_.Name -match 'prod'}
You can have a look at Matching Operators from about_comparison_operators for more information.
I am trying to use a code as follows, to locate files with specific strings, extension and lastwritetime :
get-childitem C:\users\nila9\Downloads -filter *.mkv -recurse
| where-object { $_.Name -match ("*bluray*" -and "*1080*") -and $_.lastwritetime -match "11/20/2020" }
The code is meant to first filter all files in the downloads folder with the extension *.mkv and then further shortlist for filenames containing the string "bluray" and "1080" and modified after the specified date.
While this code does not return any error, it does however not execute and releases the control to the prompt.
Is there someplace I am getting it wrong?
Thanks
As Lee_Dailey pointed out, -match uses regex and needs a different syntax. Your code needs a different operator that handles wildcards (*) and for that, there is -like
Also, you should not try to compare a DateTime object with a string, so -match is no good for that either.
If a filename needs BOTH bluray AND 1080, you can change the code to
$refDate = (Get-Date -Year 2020 -Month 11 -Day 20).Date # set time part to all 0 (--> midnight)
Get-ChildItem -Path 'C:\users\nila9\Downloads' -Filter '*.mkv' -Recurse |
Where-Object { $_.Name -like "*bluray*" -and $_.Name -like "*1080*" -and $_.LastWriteTime -ge $refDate }
If however the file needs to have bluray OR 1080 in its name, you can use -match on that part:
$refDate = (Get-Date -Year 2020 -Month 11 -Day 20).Date # set time part to all 0 (--> midnight)
Get-ChildItem -Path 'C:\users\nila9\Downloads' -Filter '*.mkv' -Recurse |
Where-Object { $_.Name -match "bluray|1080" -and $_.LastWriteTime -ge $refDate }
The pipe symbol | in regex is the OR operator
I have a list of users that I am storing in a text file. I am trying to update the text file so it removes any user that match $NotExpiring users variable, which is a collection. I just can't figure out how I would update the text file properly if more than one user needs to be removed from text file.
Below is the full function. You can ignore most of it Just look under #Stuck Here to get to the point.
function Get-NotExpiring{
$NotExpiring=New-Object System.Collections.Generic.List[System.Object]
$MatchedUser=New-Object System.Collections.Generic.List[System.Object]
$textfiles = Get-ChildItem $email_dir
#Day of Span
$Days="20"
#Settings
$Date=Get-Date ((Get-Date).adddays($Days))
$Users=Get-ADUser -filter {(Enabled -eq $True) -and (PasswordNeverExpires -eq $False)} -Properties SamAccountName, DisplayName, msDS-UserPasswordExpiryTimeComputed, Mail | Where-Object { $_.DisplayName -ne $nul -and ($_."msDS-UserPasswordExpiryTimeComputed" -gt ($NotExpDate.ToFileTime()))} | Select SamAccountName, Mail, DisplayName,#{Name="ExpiryDate";Expression={([datetime]::fromfiletime($_."msDS-UserPasswordExpiryTimeComputed")).DateTime}}
#Magic
foreach ($Entry in $Users) {
$EntryDate = Get-date($Entry.ExpiryDate)
if ($EntryDate -gt $Date){
$Account = $Entry.SamAccountName
$ExpDate = $Entry.ExpiryDate
$NotExpiring.add($Account)
}
}
#STUCK HERE
foreach($file in $textfiles){
foreach ($user in $NotExpiring){
if((Get-Content "$email_dir\$file") -contains $user){
$temp_get = Get-Content $email_dir\$file | where {$_ -notmatch $user}
}}}
$temp_get}
I tried below but it doesn't seem to work if more than one user are $NotExpiring that are also in the existing textfile. Any help would be appreciated. I know this is a simple fix but I can't seem to figure it out.
Get-Content $email_dir\$file | where {$_ -notmatch $user} | Set-Content <path>.txt
I was able to achieve exactly what I needed using the following solution.
foreach($file in $textfiles){ foreach ($user in $NotExpiring){
if((Get-Content "$email_dir\$file") -contains $user){
$MatchedUser.add($user)
}}
Get-Content "$email_dir\$file" | Where {$MatchedUser -NotContains $_ } | Set Content "$temp_dir\$file"
Copy-Item -path "$temp_dir\$file" -Destination "$email_dir\$file" -ErrorAction SilentlyContinue }
Basicly you are trying to match two arrays.
With where you do it foreach object. Now you have to match the single object $_ with the array $user.
Use:
...| where {$_ -notin $user}
or
...| where {$user -notcontains $_}
In my Azure dev/test lab (DTL), there are many resources which were not tagged. How can I get a list of all untagged resources under DTL/resource group?
Here's a simple PowerShell loop to get untagged resources.
$resources = Get-AzureRmResource
foreach($resource in $resources)
{
if ($resource.Tags -eq $null)
{
echo $resource.Name, $resource.ResourceType
}
}
Other ways to query this information and also set tags programmatically or as part of resource deployments are described here.
If you want to avoid the situation of ending up with untagged resources, you could enforce a customized policy that all resources should have a value for a particular tag.
Here is the idiomatic PowerShell to supplement #huysmania's answer which is expressed in procedural language mindset (and updated for the new PowerShell Az cmdlets):
Get-AzResource | Where-Object Tags -eq $null | Select-Object -Property Name, ResourceType
and the terse (alias) form:
Get-AzResource | ? Tags -eq $null | select Name, ResourceType
I usually just run this command to output a table of untagged resources using Get-AzResource. It filters Azure resources with tags that are $null or empty using Where-Object.
Get-AzResource `
| Where-Object {$null -eq $_.Tags -or $_.Tags.Count -eq 0} `
| Format-Table -AutoSize
If you want to list untagged resources for a specific resource group, you can just add the -ResourceGroupName switch to Get-AzResource.
$resourceGroupName = "My Resource Group"
Get-AzResource -ResourceGroupName $resourceGroupName `
| Where-Object {$null -eq $_.Tags -or $_.Tags.Count -eq 0} `
| Format-Table -AutoSize
Note: The above uses the newer Azure PowerShell Az module, which is replacement for AzureRM.
<#Bellow is PowerShell script to locate untagged resources -
you may change the script out put as per your requirement.
Hope must be helpful. Thanks!#>
Write-Host "List all resource where Tag value is not Set"
Write-Host "********************************************"
#Fetch all resource details
$resources=get-AzureRmResource
foreach ($resource in $resources) {
$tagcount=(get-AzureRmResource | where-object {$_.Name -match $resource.Name}).Tags.count
if($tagcount -eq 0) {
Write-Host "Resource Name - "$resource.Name
Write-Host "Resource Type and RG Name : " $resource.resourcetype " & " $resource.resourcegroupname "`n"
}
}
This link has the solution for this question. It beautifully explains assigning and querying tags using powershell.
$resourceGroupName = 'InternalReportingRGDev'
$azureRGInfo = Get-AzureRmResourceGroup -Name $resourceGroupName
foreach ($item in $azureRGInfo)
{
Find-AzureRmResource -ResourceGroupNameEquals $item.ResourceGroupName | ForEach-Object {Set-AzureRmResource -ResourceId $PSItem.ResourceId -Tag $item.Tags -Force }
}