Search in bindings with get-website? - iis

Why can't I do a simple:
Get-Website | where { $_.Bindings -like "*DOMAIN*" }
On the Bindings? But it works fine on the Name and Physical Path?
Any way to do a search on the Bindings with get-website?

Because there can be multiple bindings. You have to iterate through each of them:
Get-Website |
Select-Object Bindings |
Where { $_.BindingInformation -like '*DOMAIN*' }

Related

Powershell script to get all parent resources

Good day,
I am trying to figure out a way to get all the parent objects in my azure subcription to a csv from Azure.
By parent object, I am refering to objects like, VMs, Webapps, Kubernetes Clusters, ect. I want to strip away any data that is deemed illrevelant like Nics, PIPs, storage disks, ect. I am not super proficent in powershell. and I am not sure how to tackle this.
I have an azure workbook that I created that gives a good overview in a nice format, I would like to export the entire workbook for offline viewing but that doesn't seem to be possible.
Any help would be greatly appreiciated.
So, what's an "interesting" resource to you may not be to the next person, and vice versa - in some cases, for example, I may set up NICs independently of my VMs, and want to see them. I don't think there's a way to automatically get just the things you want. What you could do is create a list of resources that are interesting to you (by type), and then use Powershell to create your report:
Get 'em all and filter 'em
$resourceTypes = #(
'Microsoft.Compute/virtualMachines',
'Microsoft.Sql/servers',
'Microsoft.Sql/servers/databases'
)
$resources = #()
Get-AzResource | ForEach-Object {
if ($resourceTypes -contains $_.resourceType) {
$resources += [PSCustomObject] #{
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
}
}
}
$resources | Sort-Object ResourceType, ResourceGroupName, ResourceName |
Export-Csv -Path <path to>\resources.csv
Get 'em type by type (this one loops through subscriptions to which you have access, will print out a line with the current context on each subscription, will restore context to the current subscription when done)
$resourceTypes = #(
'Microsoft.Compute/virtualMachines',
'Microsoft.Sql/servers',
'Microsoft.Sql/servers/databases'
)
$resources = #()
$currentContext = Get-AzContext
try {
Get-AzSubscription | ForEach-Object {
$_ | Set-AzContext
$subscriptionName = $_.Name
$resourceTypes | ForEach-Object {
Get-AzResource -ResourceType $_ | ForEach-Object {
$resources += [PSCustomObject] #{
SubscriptionName = $subscriptionName
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
}
}
}
}
} finally {
$currentContext | Set-AzContext
}
$resources | Sort-Object ResourceType, SubscriptionName, ResourceGroupName, ResourceName |
Export-Csv -Path <path to>\resources.csv
Whichever approach you choose, just customize the $resourceTypes list to contain just the resource types that you want.
To get a list of resource types, I do something like this:
Get-AzResourceProvider -ProviderNamespace Microsoft.Sql |
Select ProviderNamespace -Expand ResourceTypes |
Select #{ L="Provider"; E={ "$($_.ProviderNameSpace)/$($_.ResourceTypeName)" } }
Leave off the -ProviderNamespace Microsoft.Sql if you want to get all resource types, but that will be a long list.

PowerShell Script getting JSON output to use in API

I am running a PowerShell script on a server to check on other machines on the network.
I want the result of the check to be outputted in JSON format so I can send this JSON data via an api request to a web dashboard build with angular.
My set up:
Get-Request from Angular front end -> Express server -> run PowerShell script with Node-Powershell
Now I want to return the result in proper format to be used in the front end. What is the best way to accomplish this? I want to use the data to fill a material data table.
PowerShell Script status.ps1:
$Computers = #('ExampleComputer01', 'ExampleComputer02', 'ExampleComputer03', 'ExampleComputer04')
foreach ($computer in $Computers) {
gsv -cn $computer -Name ExampleProgram -ErrorAction 'SilentlyContinue'| select-object machinename, status | ConvertTo-Json
}
Api from express server.js (using Node-Powershell):
app.get('/api/psjson', (request, response) => {
ps.addCommand('./status.ps1');
ps.invoke().then(output => {
console.log(output);
response.send(JSON.parse(output));
}).catch(err => {
console.log(err);
response.send(err);
ps.dispose();
});
});
I tried using | ConvertTo-Json inside the loop but it is causing in error in node:
SyntaxError: Unexpected token { in JSON at position 55
at JSON.parse ()
Please try the following:
$Computers = #('ExampleComputer01', 'ExampleComputer02', 'ExampleComputer03', 'ExampleComputer04')
$Results = #()
foreach ($computer in $Computers) {
$Result = $null
$Result = gsv -cn $computer -Name ExampleProgram -ErrorAction 'SilentlyContinue'| select-object machinename, status
If ($Result -ne $null){
$Results += $Result
}
}
$Results | ConvertTo-Json
This builds an array of the results and then converts the array to JSON.
I think the issue you are experiencing is due to converting inside a loop and therefore the structure is incorrect.
CraftyB's answer diagnoses the problem correctly, but there's a simpler, more PowerShell-idiomatic solution that uses a single pipeline:
$computers = 'ExampleComputer01', 'ExampleComputer02', 'ExampleComputer03', 'ExampleComputer04'
gsv -cn $computers -Name Example -ErrorAction SilentlyContinue |
| Select-Object machinename, status |
ConvertTo-Json
The crucial aspect is that all input objects are passed to a single ConvertTo-Json call - see the bottom section for an explanation.
In Windows PowerShell, Get-Service (gsv) the -ComputerName (-cn) parameter directly accepts an array of computer names.
Note: In PowerShell (Core) 7+, this form of remoting is no longer supported, so there is no -ComputerName parameter; there, assuming that the target computers are set up for PowerShell remoting, you could use:
Invoke-Command -ComputerName $computers { Get-Service -Name Example -ErrorAction SilentlyContinue }
As for what you tried:
If you call ConvertTo-Json inside a loop, per input object, you will implicitly output multiple, independent JSON strings instead of a single JSON string representing the input objects as a JSON array:
Given the following sample input objects:
$objects = [pscustomobject] #{ foo=1 }, [pscustomobject] #{ foo=2 }
It is the difference between:
# !! BROKEN: *multiple* ConvertTo-Json calls.
# !! When the result is stringified, you get a space-separated list of the
# !! individual JSON strings, which is NOT valid JSON.
PS> #"
$(
foreach ($object in $objects) { $object | ConvertTo-Json -Compress }
)
"#
{"foo":1} {"foo":2} # NOT valid JSON.
and:
# OK: *Single* ConvertTo-Json call, which outputs a valid JSON array.
PS> $objects | ConvertTo-Json -Compress
[{"foo":1},{"foo":2}] # OK: valid JSON array.

How compare output returned from powershell cmdlet with a string

I have the following code:
$RecipientType = Get-Recipient $Name | Select-Object -Property RecipientType
if ($RecipientType.Equals("UserMailbox")) {
Write-Host "Mailbox is OnPrem"
}
I want to compare RecipientType value with string "UserMailbox", but it's not working...
For simplicity I'd use this:
if ((Get-Recipient $identity).RecipientType -eq 'usermailbox') {
Write-Host 'Mailbox is OnPrem'
}
Here instead of using Select-Object -Property, use Select-Object -ExpandProperty because Select-Object returns an object. It can be done as below:
$RecipientType = (Get-Recipient $Identity | Select-Object -ExpandProperty RecipientType)
if ($RecipientType.Equals("UserMailbox")) {
Write-Host "Mailbox is OnPrem"
}

Composing a script in Powershell V3

I would like to know how i can create a script using powershell v3 to obtain the names of all the SQL instances. for example Environment 23Dev would have two virtual boxes. ASNAV-DEVSQL-23
and ASNAV-DEVWEB-23. I want to return the info ASNVA-DEVSQL-23 all the way up to Environment 50?
Can anyone assist with this?
Regards,
Joe
here is an example that will list sql instance of SQLSERVER1 and SQLSERVER2 :
"SQLSERVER1","SQLSERVER2" | % {
invoke-command -computername $_ -scriptblock{
"SERVER $env:computername"
(get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
}
}
This one-liner will list all your local instances in the form of a PowerShell object:
[System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() | Format-Table -Auto
Taken from: http://tangodude.wordpress.com/2014/02/07/list-local-sql-server-instances-with-powershell/
Edit:
This bit of code should work better than the previous one:
$Current = Get-Location;
Import-Module SQLPS -DisableNameChecking;
Set-Location $Current;
[Microsoft.SqlServer.Management.Smo.SmoApplication]::EnumAvailableSqlServers()
Edit:
This is using WMI to query the services on the target computer.
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | Out-Null;
$MC = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer("COMPUTER_NAME_HERE");
foreach ($Instance in ($MC.Services | Where-Object { $_.Type -Eq "SqlServer" }))
{
Write-Host $Instance.Name;
}

Powershell script to Find folders which have "Everyone" access and how to delete it

Need a Power Shell Script to find on a remote server which folders have "Everyone" access and How do I takeout this particular access (Remove Everyone group from Security)?
Something along these lines?
# 1. Get list of folders
$FolderList = Get-ChildItem -Path c:\test\everyone -Directory -Recurse;
# 2. Iterate over folders and remove 'everyone' rules
foreach ($Folder in $FolderList) {
$Acl = Get-Acl -Path $Folder.FullName;
$Everyone = $Acl.Access.Where({ $PSItem.IdentityReference -eq 'Everyone' });
foreach ($Ace in $Everyone) {
[void] $Acl.RemoveAccessRule($Ace);
}
Set-Acl -Path $Folder.FullName -AclObject $Acl;
}
IMPORTANT: This script requires PowerShell version 4.0, as it uses the Where "method syntax."
Translating Trevor's solution to PowerShell v2/v3:
$rootFolder = '\\server\c$\some\folder'
# get locale-specific name for 'Everyone' security principal
$sid = New-Object Security.Principal.SecurityIdentifier('S-1-1-0')
$everyone = $sid.Translate([Security.Principal.NTAccount]).Value
Get-ChildItem $rootFolder -Recurse | ? { $_.PSIsContainer } | % {
$acl = Get-Acl $_.FullName
$acl.Access | ? { $_.IdentityReference -eq $everyone } | % {
$acl.RemoveAccessRule($_)
}
Set-Acl $_.FullName -Acl $acl | Out-Null
}
In PowerShell v3 you can replace | ? { $_.PSIsContainer } with -Directory.
Note that this won't remove Everyone ACEs on the root folder itself, and it also won't remove inherited Everyone ACEs.

Resources