I want to connect to CosmosDB in Azure Portal to fetch data using a query. I need to do this using Azure Powershell (Runbook). Please suggest how to establish connection and execute some random query using Azure Powershell.
Thanks!!
$cosmosDBAccountKey = Get-AzCosmosDBAccountKey -ResourceGroupName $resourceGroupName -Name $accountName
$key = $cosmosDBAccountKey.PrimaryMasterKey
$primaryKey = ConvertTo-SecureString -String $key -AsPlainText -Force
$cosmosDbContext = New-CosmosDbContext -Account $accountName -Database $databaseName -Key $primaryKey
Get-CosmosDbDocument -Context $cosmosDbContext -CollectionId $containerName
The only way to do this is to call Cosmos DB using it's REST API from PowerShell. The link will take you to samples that show simple point operations. You will need to reference the REST API for query here.
Another option may be to explore creating a custom cmdlet where you can use the Cosmos DB .NET SDK to query your data then return via your custom cmdlet.
The Cosmos DB PowerShell module from the gallery works great for that.
$cosmosDBAccountName = "..."
$cosmosDBDatabaseName = "..."
$cosmosDBContainerName = "..."
# First get your account key
$cosmosDBAccountKey = Get-AzCosmosDBAccountKey -ResourceGroupName $rgName -Name $cosmosDBAccountName
# Then establish a context
$primaryKey = ConvertTo-SecureString -String $cosmosDBAccountKey -AsPlainText -Force
$cosmosDbContext = New-CosmosDbContext -Account $cosmosDBAccountName -Database $cosmosDBDatabaseName -Key $primaryKey
# Finally issue your query
$query = "SELECT * FROM customers c WHERE c.deviceid = '0' ORDER BY c.windowend DESC"
(Get-CosmosDbDocument -Context $cosmosDbContext -CollectionId $cosmosDBContainerName -Query $query) | Select-Object {$_.deviceid,$_.jobname}
Related
I'm trying to use powershell to write a script that calls net.exe's delete on a collection of computers meeting the specific case of having 3 or fewer files open. I'm fairly new at this, obviously, as I'm getting odd errors.
Using the example at Microsoft's blog I made the function below out of net session.
Function Get-ActiveNetSessions
{
# converts the output of the net session cmd into a PSobject
$output = net session | Select-String -Pattern \\
$output | foreach {
$parts = $_ -split "\s+", 4
New-Object -Type PSObject -Property #{
Computer = $parts[0].ToString();
Username = $parts[1];
Opens = $parts[2];
IdleTime = $parts[3];
}
}
}
which does produce a workable object that I can apply logic to.
I can use
$computerList = Get-ActiveNetSessions | Where-Object {$_.Opens -clt 3} | Select-Object {$_.Computer} to pull all computers with less than three opens into a variable, too.
What fails is the loop below
ForEach($computer in $computerList)
{
net session $computer /delete
}
with the error
net : The syntax of this command is:
At line:5 char:5
net session $computer /delete
CategoryInfo :NotSpecified (The syntax of this command is::String) [], RemoteException
FullyQualifiedErrorId : NativeCommandError
NET SESSION
[\\computername] [/DELETE] [/LIST]
Trying to run it with a call of $computer = $computer.ToString() ahead of the execution so it sees a string causes the script to hang without dropping the sessions, forcing me to close and reopen the ISE.
What should I do to get this loop working? Any help is appreciated.
Net session expects a \\ before the server name, it looks like. Have you given that a try?
I am trying to encrypt the web.config file after deploying automatically.
As per the Link :https://blogs.iis.net/msdeploy/archive/2013/07/09/webdeploy-3-5-rtw.aspx
I am using below command:
msdeploy.exe –verb:sync –source:iisapp=”sourceTestSite” –dest:iisapp=”destinationTestSite” –EnableRule:EncryptWebConfig
But then I am getting error:
Error Code: ERROR_FAILED_TO_ENCRYPT_WEB_CONFIG
I do not want to first encrypt and then deploy. I am thinking to run deployment script and after deployment it should encrypt automatically probably using MSDEploy command.
I tried below threads but did not get any help:
Failed to encrypt destination web.config when using MS build plugin in Jenkins
Also I wanted to keep my secret file in separate location but I found encryption process will not work for that
How to encrypt a file linked to a web.config
This time I am trying to run command on remote server to encrypt the web.config file by using below code. I am running below code in my machine and trying to encrypt the web.config file present on my myRemoteServer.
$currentDirectory = (Get-Location)
$user = "domain1\username1"
$section = "appSettings"
$app= "/MyWeb"
$version="v4.0.30319"
$computername ="myRemoteServer"
$pwd = ConvertTo-SecureString -String "mysecret#11" -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$pwd
$encryptcmd1= Set-Location "C:\windows\Microsoft.Net\Framework\$version"
$encryptCmd2 = ".\aspnet_regiis.exe -pe ""appSettings"" -app ""/MyWeb"""
$encryptCmd = "$encryptcmd1 $encryptcmd2"
try
{
invoke-command -ComputerName $computername -Credential $credential -ScriptBlock {$encryptCmd}
}
catch
{
Log-Message $_
}
Set-Location $currentDirectory
It doesn't throw any exception. However it is not working and not encrypting web.config file on that server.
I want to know where / what is wrong here.
his function will encrypt a sections of a web.config file.
function Encrypt-ConfigurationSection([int] $id, [string] $app, [string] $section, [string] $version){
$currentDirectory = (Get-Location)
Set-Location "C:\windows\Microsoft.Net\Framework\$version\"
.\aspnet_regiis.exe -pe $section -app $app -site $id -prov "RsaProtectedConfigurationProvider"
Set-Location $currentDirectory
}
Example call
Encrypt-ConfigurationSection 1 ‘/WebApplication1’ ‘connectionStrings’ ‘v4.0.30319’
This function will decrypt a sections of a web.config file.
function Decrypt-ConfigurationSection([int] $id, [string] $app, [string] $section, [string] $version){
$currentDirectory = (Get-Location)
Set-Location "C:\windows\Microsoft.Net\Framework\$version\"
.\aspnet_regiis.exe -pd $section -app $app -site $id
Set-Location $currentDirectory
}
Example Call
Decrypt-ConfigurationSection 1 ‘/WebApplication1’ ‘connectionStrings’ ‘v4.0.30319’
I got help from this website:
https://joshjoubert.wordpress.com/2013/03/28/encrypting-and-decrypting-sections-of-a-web-config-with-powershell/
I am not able to download e.g. Google Chrome via Internet Explorer.
I also have a R-script that I'm able to run on my local PC, but not on my EC2 windows instance. The R-script logs in to Google Trends and pulls out search terms.
Does anyone have an idea of what is going on here?
try to install chrome using power-shell. found working solution here.
https://superuser.com/a/1396175/904062
Open powershell and hit this command
$LocalTempDir = $env:TEMP; $ChromeInstaller = "ChromeInstaller.exe"; (new-object System.Net.WebClient).DownloadFile('http://dl.google.com/chrome/install/375.126/chrome_installer.exe', "$LocalTempDir\$ChromeInstaller"); & "$LocalTempDir\$ChromeInstaller" /silent /install; $Process2Monitor = "ChromeInstaller"; Do { $ProcessesFound = Get-Process | ?{$Process2Monitor -contains $_.Name} | Select-Object -ExpandProperty Name; If ($ProcessesFound) { "Still running: $($ProcessesFound -join ', ')" | Write-Host; Start-Sleep -Seconds 2 } else { rm "$LocalTempDir\$ChromeInstaller" -ErrorAction SilentlyContinue -Verbose } } Until (!$ProcessesFound)
The Install-ChocolateyZipPackage commandlet does not seem to support basic authentication when it comes to downloading files, i.e. via an URL such as https://user:password#example.com/file.zip. How can I work around this in my Chocolatey install script, i.e. download the file in question (e.g. https://user:password#example.com/file.zip) before I install it via Install-ChocolateyZipPackage?
Thomas put up a good answer in the group forum - https://groups.google.com/forum/#!msg/chocolatey/e4lcPIrLhis/vfSUVe0SZcIJ
As far as I know, authentication is not supported. But you could
specify wget as dependency and use that to download the file.
I use it in one of my packages for authentication and it works fine:
https://chocolatey.org/packages/rukerneltool#files (look at chocolateyInstall.ps1)
On Linux, wget would be the first choice to handle such things in a
Bash script.
But if the software you want to make a package of is Open Source, you
could integrate it directly into the package. That makes it easier.
Code for this is (in case it is later changed:
$webClient = New-Object System.Net.WebClient
$webClient.Credentials = New-Object System.Net.Networkcredential($username, $password)
Write-Output $('Downloading' + $url + '…')
$webClient.DownloadFile($url, $zipFilePath)
I use a similar way without wget, to fetch artifacts from our company's buildserver
$packageName = 'mycompanypackage'
$installerType = 'exe'
$username = 'chocolatey'
$password = '************'
$url = 'http://bamboo.mycompany.com/browse/DP-RS/latestSuccessful/artifact/JOB1/Setup/setup.exe'
$downloadFile = $url.Substring($url.LastIndexOf("/") + 1)
$url = $url+'?os_authType=basic'
$url64 = $url
$silentArgs = '/VERYSILENT /NORESTART /SUPPRESSMSGBOXES'
if (Test-Path "$downloadFile") {Remove-Item "$downloadFile"}
$webclient = new-object System.Net.WebClient
$credCache = new-object System.Net.CredentialCache
$creds = new-object System.Net.NetworkCredential($username, $password)
$credCache.Add($url, "Basic", $creds)
$webclient.Credentials = $credCache
$webclient.DownloadFile($url, $downloadFile)
Install-ChocolateyInstallPackage "$packageName" "$installerType" "$silentArgs" "$downloadFile"
Would someone explain how to enable Amazon S3 server-side encryption in a PowerShell script? I'm using the sample code below but when I check encryption in the AWS Console or Cloudberry S3 Explorer Pro the encryption type is still set to 'none'. Using AWS / Cloudberry to do this manually after files are uploaded isn't feasible because the script is to be deployed to 200+ servers, each with it's own bucket in S3. Here's a snippet of code from the script:
$TestFile="testfile.7z"
$S3ObjectKey = "mytestfile.7z"
#Create Amazon PutObjectRequest.
$AmazonS3 = [Amazon.AWSClientFactory]::CreateAmazonS3Client($S3AccessKeyID,$S3SecretKeyID)
$S3PutRequest = New-Object Amazon.S3.Model.PutObjectRequest
$S3PutRequest.BucketName = $S3BucketName
$S3PutRequest.Key = $S3ObjectKey
$S3PutRequest.FilePath = $TestFile
$S3Response = $AmazonS3.PutObject($S3PutRequest)
I've tried inserting the following without success (before the $S3Response line):
$S3PutRequest.ServerSideEncryption
When the above is added I get this message in the output but the file is still not tagged as encrypted on S3:
MemberType : Method
OverloadDefinitions : {Amazon.S3.Model.PutObjectRequest WithServerSideEncryptionMethod(Amazon.S3.Model.ServerSideEncryptionMethod encryption)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : Amazon.S3.Model.PutObjectRequest WithServerSideEncryptionMethod(Amazon.S3.Model.ServerSideEncryptionMethod encryption)
Name : WithServerSideEncryptionMethod
IsInstance : True
Can anyone tell me what I'm doing wrong? Many thanks in advance.
You should add:
$S3PutRequest.WithServerSideEncryptionMethod([Amazon.S3.Model.ServerSideEncryptionMethod]::AES256)
Or:
$S3PutRequest.ServerSideEncryptionMethod = [Amazon.S3.Model.ServerSideEncryptionMethod]::AES256
If you are using CloudBerry, it has its own PowerShell snapin
Add-PSSnapin CloudBerryLab.Explorer.PSSnapin
$s3 = Get-CloudS3Connection -Key XXXXXXX -Secret YYYYYYY
$destFolder = $s3 | Select-CloudFolder -path "mybucket"
$local = Get-CloudFilesystemConnection
$srcFolder = $local | Select-CloudFolder -path "c:\myzips"
$srcFolder | Copy-CloudItem $destFolder -filter "testfile.7z" -SSE
Notice -SSE parameter in the Copy-CloudItem command.
Some helpful examples can be found on their blog: http://blog.cloudberrylab.com/search?q=powershell