I use the below Windows PowerShell script to extract all members of particular Yammer group and store the output as .csv file on my local machine.
What I need is to save this output as a table in Azure SQL DB. What would be the right way to approach this:
Amend the below script to save data in Azure Table?
Use some Azure SQL functionality?
Anything else?
I would appreciate your help,
$GroupId=xxxxx
$Token = "xxxx"
$Headers = #{ "Authorization" = "Bearer "+$Token }
$GroupCycle = 1
DO
{
$GetMoreGroupsUri = "https://www.yammer.com/api/v1/users/in_group/$GroupId.xml?page=$GroupCycle"
write-host ("REST API CALL : $GetMoreGroupsUri")
[xml]$Xml = ((Invoke-WebRequest -Uri $GetMoreGroupsUri -Method Get -Headers $Headers).content)
$YammerGroups += $Xml.response.users.user
$GroupCycle ++
$GroupCount += $Xml.response.users.user.count
write-host ("GROUPMEMBER COUNT : $GroupCount")
}
While ($Xml.response.users.user.count -gt 0)
$YammerGroups | Where {$_} | Export-Csv "$GroupId.csv" -Delimiter ","
I would approach this problem slightly differently. I would use Azure to store the value of the variables I needed and keep the script somewhere else that is cloud accessible, Sharepoint comes to mind, so does GIT.
Here is the documentation on the Azure DB PowerShell Module AzTable:
https://learn.microsoft.com/en-us/azure/storage/tables/table-storage-how-to-use-powershell
Here are a couple of highlights:
#Install Module
Install-Module AzTable
#Get Table Contents
Get-AzStorageTable –Context $ctx | select Name
The Module is very well defined. I encourage you to take a look at all of the different calls listed in the Microsoft Doc.
Here is a breakdown:
Use Sharepoint or Git to store your script
If you want to store values, Azure DB is great. Use the PowerShell Module AzTable to interact with it. You can write and read tables as you see fit.
If you need dynamic variables, simply adjust the code to read the table value and variablize it. Should be easy to accomplish in some of the loops.
Related
I need the list of available versions for a Universal Package stored in Azure Devops. My thought is to call the REST API Get Package Versions to get a list of the versions for packages on a feed.
GET https://feeds.dev.azure.com/{organization}/{project}/_apis/packaging/Feeds/{feedId}/Packages/{packageId}/versions?api-version=5.1-preview.1
The problem is that it requires a packageId, which is the GUID and I only know the name. The only way I've figured out so far to convert a package name to a GUID is using "Get Packages" but that returns every package on the feed (which for me includes thousands of NPM packages) and that makes the download very large for the handful of items I need. Is there some way to extract the packageId for a given package name? Or is there a better way to extract all the versions for a package?
Someone pointed out to me that the Get Packages API has options for IncludeAllVersions and packageNameQuery to achieve what I want rather than using GetAllVersions.
https://feeds.dev.azure.com/{organization}/{project}/_apis/packaging/Feeds/{feedId}/Packages?includeAllVersions=true&packageNameQuery={packageName}&protocolType=nuget
I assume you have checked some docs and found there's no direct API can let you get specified packaged ID, right? Also, as the doc said, the package name could not be used in this API:
In fact, you have very close to the answer. Just add some filter while you running Get Packages. But this need you execute some script in Powershell command line or Powershell ISE which is the most convenient approach can for you use. You can also run below script in Azure Devops pipeline, but compare with running in command line, it is a bit cumbersome.
Run below script in your Powershell command line or Powershell ISE:
$token = "{your PAT token}"
$url = 'https://feeds.dev.azure.com/{org name}/_apis/packaging/Feeds/{feed ID}/packages'
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get
$results = $response.value | Where {$_.name -eq "{Package Name}"} #|
Write-Host "results = $($results | ConvertTo-Json -Depth 100)"
Note: In the above script, you just need to replace the value of PAT token, Organization name and your package name.
Then you will get the info of the specified package, and you can copy the package ID from the command line and apply it in another place :
Note: The above script can also be applied in the Powershell task of Azure Devops without change anything.
I have a powershell script that provides SQL Agent Job information. The script is meant to monitor the jobs and tell me if they failed the last time they ran. However i also want to know which was the last run step. and i can't seem to figure out how.
I am querying the Sql server mangement object, because it needs to be usable on multiple remote servers (remote connections) and i wish to avoid running SQL scripts.
Keep in mind i'm rather new to powershell.
This is the code i have so far: And i have loaded the SMO libraries, i just didn't show it the copied script.
## Get Jobstep Class SMO
Push-Location; Import-Module SQLPS -DisableNameChecking; Pop-Location;
$JobStep = New-Object microsoft.sqlserver.management.smo.agent.jobstep
## Run the select from the local SQL server management objects
$SQLSvr = "."
$MySQLObject = new-object Microsoft.SqlServer.Management.Smo.Server `
$SQLSvr;;
$Select = ($MySQLObject.JobServer.jobs) `
| Select Name, isEnabled, `
lastRunDate, lastRunOutCome, NextRunDate `
| Where-Object {$_.LastRunDate -ge ((Get-Date).adddays(-2)) } `
| ft -AutoSize;
$Select
The push-location section is meant to get the correct smo class for selecting the job step (unsure if it is right), however i haven't added anything from it.
Now the script does work, i get no errors and i get returned the overall information i want, but i cannot figure out how to add the jobstep - and i have consulted google. I'm well aware that i need to add more to the select, but what is the issue for me. So, how do i extract the last run job step from SQL Agent job, using the SMO, and add it to the above script?
You can use the SqlServer module from the PowerShell Gallery (Install-Module SqlServer), and then something like:
$h = Get-SqlAgentJobHistory -ServerInstance servername -JobName jobname
$h[0] will give you the last step ran.
This will give you the result in the format you wanted:
Get-SqlAgentJob -ServerInstance servername |
Where-Object {$_.LastRunDate -ge ((Get-Date).AddDays(-2))} | ForEach-Object {
$h = Get-SqlAgentJobHistory -ServerInstance servername -JobName $_.Name
[PSCustomObject]#{
Name = $_.Name
IsEnabled = $_.IsEnabled
LastRunDate = $_.LastRunDate
LastRunOutcome = $_.LastRunOutcome
NextRunDate = $_.NextRunDate
LastRunStep = $h[0].StepName
}
}
In PowerShell, using Get-PowerBIWorkspace -Scope Organizition, I can pull a list of workspaces organization-wise. Some workspaces returned are personal workspaces (e.g. Type = "PersonalGroup", Name = "PersonalWorkspace Ben").
Is there a way to fetch any details beyond first name about the owner of the personal workspace (e.g. last name, domain user name, etc.)?
I'm looking for some way to figure out which "Ben" (in the case of the example) owns the workspace when there can be several people with that first name in the company.
Did you try their restmethod cmdlet? Looks like all other PowerBI cmdlets are just wrappers of their REST API. Try this:
Login-PowerBI
# $myworkspace = Invoke-PowerBIRestMethod -Url 'Groups' -Method Get | ConvertFrom-Json
$workspaces = Invoke-PowerBIRestMethod -Url 'admin/Groups' -Method Get | ConvertFrom-Json
Then browse the output object in powershell ise or vscode.
In trying to design a simplified script for use with the office 365 graph API I can't seem to find any way to call it from a simplified outset.
For the use that I have intended for it I really don't want to take the time to build and compile an actual program when everything else can be done from powershell or a batch script.
In specific, I really only want to be able to call the graph API for a list of groups and store the result (in an array or text file). Is it possible to call the graph API from powershell or command line and if so, how?
In specific, I really only want to be able to call the graph API for a list of groups and store the result (in an array or text file).
If you just need to export a list of groups. I suggest you using the Azure Active Directory PowerShell.
$msolcred = get-credential
connect-msolservice -credential $msolcred
Get-MsolGroup | Out-File C:\Workbench\temp\tests\export.txt
Is it possible to call the graph API from powershell or command line and if so, how?
Yes, it is possible, to call the REST API:
First, you need to Obtaining an Access Token
Then, use the Invoke-RestMethod to call Graph API.
Invoke-RestMethod -Uri $uri -Headers #{Authorization = "Bearer {your_access_token}"}
You can use the PSMSGRAPH module for this. Can be download from the gallery
You must register an application in Azure to authenticate and delegate the necessary right to your app. You can do it at the appreg portal
Once this is done you just need to auth and run your request.
When running the code you will have to provide a credential to authorize.
$username = 'entertheappidhere'
$password = 'entertheapppaswordhere' | ConvertTo-SecureString -AsPlainText -Force
$ClientCredential = New-Object -TypeName
System.Management.Automation.PSCredential($username,$password)
$GraphAppParams = #{}
$GraphAppParams.Add('Name','Office365TenantMigration')
$GraphAppParams.Add('ClientCredential',$ClientCredential)
$GraphAppParams.Add('RedirectUri','https://localhost/')
$GraphAppParams.Add('Tenant','yourtenant.onmicrosoft.com')
$GraphApp = New-GraphApplication #GraphAppParams
# This will prompt you to log in with your O365/Azure credentials.
$AuthCode = $GraphApp | Get-GraphOauthAuthorizationCode
$GraphAccessToken = $AuthCode | Get-GraphOauthAccessToken -Resource 'https://graph.microsoft.com/'
$GraphAccessToken | Export-GraphOAuthAccessToken -Path 'f:\O365Report\AccessToken.XML'
$GraphAccessToken = Import-GraphOAuthAccessToken -Path 'f:\O365Report\AccessToken.XML'
$GraphAccessToken | Update-GraphOAuthAccessToken -Force
### Run the query
Invoke-GraphRequest -Uri "https://graph.microsoft.com/v1.0/groups"-Method GET -AccessToken $GraphAccessToken
I'm trying to move my tools to powershell, can this be done in PowerShell? the bit I'm really interested in is:
IEventService es = tfs.GetService(typeof(IEventService)) as IEventService;
List<Subscription> ls = es.GetAllEventSubscriptions().ToList();
Edit: what I really want to do might be using a .NET assembly from powershell and this might then be a duplicate of Using .NET library from PowerShell
Here is a TFS API in PowerShell function that I found on a blog long ago that will get you started. I've posted it to a GitHub Gist. Basically you ensure you've loaded up the TFS assemblies into the AppDomain and then you can add any TFS Service Interfaces you want to the object and just operate on them just as you would in any c# application, etc.
https://gist.github.com/3288447
Once you have the TFS object returned from the method in the Gist above, you can operate on the loaded services like so:
#use work item service
$tfs = get-tfs $env:TFSSERVERURL -silent
$project = $tfs.wit.Projects | ?{ $_.Name -eq $projectName}
#todo - replace with text for query or file read -- this is deprecated
$query = $project.StoredQueries | ?{ $_.Name -eq 'Active Bugs' }
$queryText = $query.QueryText.Replace("#project","'$projectName'")
$results = $tfs.wit.Query($queryText)
#do something with the results...
In your request above you can just alter the get-tfs method to add your service interface to the set loaded and then operate on the .NET methods much like I do in the example above.