TotalCount command in powershell - powershell

Is it possible to get the total count of records in db (5M records) using powershell?
$database = New-Object HP.HPTRIM.SDK.Database
$database.Id = "10"
$database.WorkgroupServerName = "dbnonprod"
$database.Connect()
$recordSearch = New-Object HP.HPTRIM.SDK.TrimMainObjectSearch($database, [HP.HPTRIM.SDK.BaseObjectTypes]::Record)
$recordSearch.SetsearchString("All")
$a = 0
foreach ($record in $recordSearch) {
$a+= $record.count
}
echo $a
And this is my error when trying to get the totalcount store on the db from content manager database
Content Manager Workgroup Server on 'dbnonprod' reported an error.
Could not serialize the server-side recordset. Error with SQL
Connection: The ODBC connection is not active any more, could be
forcibly closed by the server or in load balancing.

Related

EWS and AutoDiscoverURL error using Azure AD Certificate with Powershell

I've tried with and without Secret ID, and now with a self-signed Certificate and I keep getting the same error:
Exception calling "AutodiscoverUrl" with "2" argument(s): "The
expected XML node type was XmlDeclaration, but the actual type is
Element."
My PowerShell script:
$TenantId = "blahblah"
$AppClientId="blahblah"
$EDIcertThumbPrint = "blahblah"
$EDIcert = get-childitem Cert:\CurrentUser\My\$EDIcertThumbPrint
$MsalParams = #{
ClientId = $AppClientId
TenantId = $TenantId
ClientCertificate = $EDIcert
Scopes = "https://outlook.office.com/.default"
}
$MsalResponse = Get-MsalToken #MsalParams
$EWSAccessToken = $MsalResponse.AccessToken
Import-Module 'C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll'
#Provide the mailbox id (email address) to connect via AutoDiscover
$MailboxName ="email#myemaildomain.com.au"
$ews = [Microsoft.Exchange.WebServices.Data.ExchangeService]::new()
$ews.Credentials = [Microsoft.Exchange.WebServices.Data.OAuthCredentials]$EWSAccessToken
$ews.Url = "https://outlook.office365.com/EWS/Exchange.asmx"
$ews.AutodiscoverUrl($MailboxName,{$true})
I've searched that error message everywhere, and I am not getting anywhere. The error doesn't make sense, because I am not referring to XML in any way - unless it's embedded inside the EWS?
The only time this works is when I don't use either a Secret ID nor a Certificate, but the Token only lasts 1 hour! I need to make this automatic, so I can get into my mailbox and extract files from emails.
Thanks
UPDATE
So I've removed the AutoDiscoverUrl() and I now getting another error:
Exception calling "FindItems" with "2" argument(s): "The request
failed. The remote server returned an error: (403) Forbidden."
Trace log:
The token contains not enough scope to make this call.";error_category="invalid_grant"
But why when I have an Oauth token!?
My code in trying to open the "Inbox":
$results = $ews.FindItems(
"Inbox",
( New-Object Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList 100 )
)
$MailItems = $results.Items | where hasattachments
AutoDiscoverv1 doesn't support the client credentials flow so you need to remove the line
$ews.AutodiscoverUrl($MailboxName,{$true})
It's redundant anyway because your already setting the EWS endpoint eg
$ews.Url = "https://outlook.office365.com/EWS/Exchange.asmx"
The only time that endpoint would change is if you had mailbox OnPrem in a hybrid environment and there are other ways you can go about detecting that such as autodiscoverv2.

Parse data using Powershell and convert to Json

Background.
i have IBM CDC Replication engine and i need to check subscriptions status by using Zabbix.
Im calling subs status by cmd.exe /C "C:\Program Files\IBM\InfoSphere Data Replication\Management Console\bin\chcclp.exe" -f c:\CDC_Check.txt where CDC_Check.txt is script for that chcclp CLI
//Check the status of all subscriptions
//Source datastore: ***
//Target datastore: ***
chcclp session set to cdc;
// Turn on verbose output.
set verbose;
// Setting variables.
set variable name "ACCESS_HOSTNAME" value "";
set variable name "ACCESS_PORT" value "";
set variable name "ACCESS_USERNAME" value "";
set variable name "ACCESS_PASSWORD" value "";
set variable name "SOURCE_DATASTORE" value "";
set variable name "TARGET_DATASTORE" value "";
// Connecting to Access Server.
connect server
hostname "%ACCESS_HOSTNAME%"
port "%ACCESS_PORT%"
username "%ACCESS_USERNAME%"
password "%ACCESS_PASSWORD%";
// Connecting to the source and target datastores.
connect datastore name "%SOURCE_DATASTORE%";
connect datastore name "%TARGET_DATASTORE%";
// Setting the datastore context.
select datastore name "%SOURCE_DATASTORE%" context source;
select datastore name "%TARGET_DATASTORE%" context target;
// List replication state and latency of all subscriptions.
monitor replication;
// Disconnecting from datastores and Access Server.
disconnect datastore name "%SOURCE_DATASTORE%";
disconnect datastore name "%TARGET_DATASTORE%";
// Disconnect from Access Server and terminate the script.
disconnect server;
exit;
and im receiving following result:
Im trying to parse Subscription + Status and move it to Json for next integration with zabbix.
Im very new in PS so i still have no normal progress.
I understand idea that i need to capture anything that going under SUBSCRIPTIONS and STATE and write it to Json.
The first step would be to redirect the output of the app so you can read it in for parsing.
cmd.exe /C "C:\Program Files\IBM\InfoSphere Data Replication\Management Console\bin\chcclp.exe" -f c:\CDC_Check.txt > C:\temp\file.log
Then you can use the get Get-Content cmdlet to get it in your console session
$fileContent = Get-Content -Path "C:\temp\file.log"
Once it's in an array you can parse it like so.
$i=0
$fileContent | %{
$i++
if($_ | Select-String -Pattern "SUBSCRIPTION STATE" -CaseSensitive){
$headerIndex = $i
}
}
$headerIndex += 2 #start of report data to capture
This loop continues until it finds the blank line in the output
$hashObj= #{}
for ($x = $headerIndex; $fileContent[$x].length -gt 1 ;$x++){
$hashObj.Add("$($fileContent[$x].Substring(0,19).Trim(' '))","$($fileContent[$x].Substring(20,19).Trim(' '))")
}
#converts your hashtable to json object
$jsonObj = $hashObj | convertto-json
Not entirely sure how you need the json formatted but this will be what to expect your output to be similar to
{
"S_ACC_D": "Mirror Continuous",
"S_ACC_E": "Mirror Continuous",
"S_ACC_A": "Mirror Continuous",
"S_ACC_B": "Mirror Continuous",
"S_ACC_C": "Mirror Continuous"
}

I am Trying to connect to an existing BizTalk application and add Receive Ports and Send Ports and Parties etc

When run this I do not get a error, but when I create send ports and Receive locations I don't see anything
make sure the ExplorerOM assembly is loaded
[void] [System.reflection.Assembly]::LoadwithPartialName("Microsoft.BizTalk.ExplorerOM")
Connect to the BizTalk management database
$Catalog = New-Object Microsoft.BizTalk.ExplorerOM.BtsCatalogExplorer
$Catalog.ConnectionString = "SERVER=sql\instance; DATABASE=BizTalkMgmtDb; Integrated Security=SSPI"
Connect to an existing application in Biztalk
Create a message to let you know if powershell can't find the applicaiton on your server
If it can't find the application it gives a error and discard changes. If so it continues
$In837_2Cimor = $Catalog.Applications["In837_2Cimor"]
if ($In837_2Cimor -eq $null)
{
Write-Host "`r`nFailed to find `"In837_2Cimor`" deployed on this BizTalk server."
}
else
{
**Register a trap handler for any exceptions**
$ErrorActionPreference="silentlycontinue"
trap { "Exception encountered:`r`n"; $_; "`r`nDiscarding Changes.`r`n";$Catalog.DiscardChanges();exit; }
}
**Create a new receive port named For the new provider**
And A new receive location will also be created and associated
with the receive port.
$NewRP = $In837_2Cimor.AddNewRecievePort($false,$false)
$NewRP.Name = "RP_Pickup999_000"
Note if you don’t set the name property for the receive port,
it will create a new receive location and add it to the receive
port.
**Create a new receive location and add it to the receive port**
$NewRL = $In837_2Cimor.AddNewReceiveLocation($false,$false)
$NewRL.PrimaryTransport.TransportType = $Catalog.ProtocolTypes["FILE"]
$NewRL.PrimaryTransport.Address = "\\location\BizTalkd\"
$NewRL.SendPipeline = $Catalog.Pipelines["Microsoft.BizTalk.DefaultPipelines.PassThruTransmit"]
**Save the changes**
Write-Host "Adding $NewRP.Name..."
$catalog.SaveChanges();
Write-Host "`r`n $NewRP.Name has been created."
Create New In837 sendPorts for a new provider
$NewSP = $In837_2Cimor.AddNewSendPort($false,$false)
$NewSP.Name = "SP_999_TO_FTP_000"
$NewSP.PrimaryTransport.TransportType = $Catalog.ProtocolTypes["FILE"]
$NewSP.SendHandler = $Catalog.SendHandlers["BizTalkServerApplication"]
$NewSP.PrimaryTransport.Address = "\\location\"
$NewSP.SendPipeline = $Catalog.Pipelines["Microsoft.BizTalk.DefaultPipelines.PassThruTransmit"]
Add the filter to New send port
$NewSP.Filter = "<Filter><Group>" +
"<Statement Property='BTS.ReceivePortName' Operator='==' Value='RP_Pickup999_000'/>" +
"</Group></Filter>"
Write-Host Adding ($NewSP.Name) and ($NewRP.Name) and ($NewRL.Name) to catalog...
$Catalog.SaveChanges()

Driver not installed error when running powershell add-OdbcDsn

Problem is add-odbcdsn is returning "driver not installed error" , though I can create using the GUI. Below is a piece from my code that returns the error. I also tried to create an ODBC connection using the GUI and specifying the driver. I then do get-odbcdsn for that DSN. Use the output for that and run add-odbcdsn. This action also results in a driver not installed error.
$dsn_object = #{
Name = "123"
DriverName = "C:\app\oracle64\product\12.2.0\client64\BIN\SQORA32.DLL"
DsnType = "System"
Platform = "64-bit"
SetPropertyValue = ""
}
$dsn_values = -split #"
DisableRULEHint=T
Attributes=W
SQLTranslateErrors=F
AggregateSQLType=FLOAT
MaxTokenSize=8192
FetchBufferSize=64000
NumericSetting=NLS
ForceWCHAR=F
FailoverDelay=10
FailoverRetryCount=10
MetadataIdDefault=F
BindAsFLOAT=F
BindAsDATE=F
CloseCursor=F
EXECSchemaOpt=
EXECSyntax=F
Application Attributes=T
QueryTimeout=T
CacheBufferSize=20
StatementCache=F
ResultSets=T
MaxLargeData=0
UseOCIDescribeAny=F
Failover=T
Lobs=T
DisableMTS=T
DisableDPM=F
BatchAutocommitMode=IfAllSuccessful
Description=64 Bit TEST Oracle
ServerName=
Password=
UserID=homersimpson
DSN=64 Bit TEST Oracle
"#
$dsn_object.SetPropertyValue = $dsn_values
Add-OdbcDsn #dsn_object
I have also tried a simple example:
add-OdbcDsn -Name "TEST" -DriverName "C:\app\oracle64\product\12.2.0 \client64\BIN\SQORA32.DLL" -DsnType System
Expect the DSN to be created...
Add-OdbcDsn : The driver {C:\app\oracle64\product\12.2.0\client64\BIN\SQORA32.DLL} is not installed.
Get-OdbcDriver shows the driver is there:
Name
Value
---- -----
APILevel 1
FileUsage 0
Driver C:\app\oracle64\product\12.2.0\client64\BIN\SQORA32.DLL
ConnectFunctions YYY
CPTimeout 60
DriverODBCVer 03.51
SQLLevel 1
Setup C:\app\oracle64\product\12.2.0\client64\BIN\SQORAS32.DLL
After all that, I resolved it. I realized I was using the path to the driver as the name and not the actual name as seen in the ODBC GUI.

How to remove a permission, a member, or a role?

I have this script below to add roles and members and permissions
Import-Module sqlserver
$Server = new-Object Microsoft.AnalysisServices.Tabular.Server
$Server.Connect("SERVER\INSTANCE")
$TabDB = $SERVER.Databases["DATABASENAME"]
$AddRole = new-Object Microsoft.AnalysisServices.Tabular.ModelRole
$AddRole.Name = 'NewRole1'
$AddRole.ModelPermission="Read"
$RoleMember = New-Object Microsoft.AnalysisServices.Tabular.WindowsModelRoleMember
$RoleMember.MemberName = 'DOMAIN\ACCOUNT'
$TabDB.Model.Roles.Add($AddRole)
$AddRole.Members.Add($RoleMember)
$TabDB.Update([Microsoft.AnalysisServices.UpdateOptions]::ExpandFull)
$server.Disconnect()
How can I remove a permission, a member, and a role?
I tried this at least for the role, but the console returns back "False"
$TabDB.Model.Roles.Remove($AddRole)
When working with ssas from powershell (or C# for that matter) you can use the analysisservices namespace of microsoft:
Microsoft analysisservices.
This is an object oriented way of working with ssas databases.
This is an old script I wrote for maintainers:
function addRoleToDb {
$roleName = Read-Host "How should this role be called?"
if ($global:dataBase.Roles.findByName($roleName)) {
echo "This role already exists"
return
} elseif ($roleName -eq "") {
echo "You can't give an empty name for a role."
return
}
echo "Warning: this role will start out empty and will have to be modified in order to be used. (it wil have read permission)"
[Microsoft.AnalysisServices.Role] $newRole = New-Object([Microsoft.AnalysisServices.Role])($roleName)
$global:dataBase.Roles.add($newRole)
$dbperm = $global:dataBase.DatabasePermissions.add($newRole.ID)
$dbperm.Read = [Microsoft.AnalysisServices.ReadAccess]::Allowed
$global:dataBase.Roles.Update()
$dbperm.Update()
return
}
At this point I already had a global variable database.
This is a method that would add a role to the database. Deleting the database would work practically the same, you would get the instance of the role with:
role = database.roles.findbyname()
or
role = database.roles.findbyid()
and then
role.Drop(DropOptions.AlterOrDeleteDependents);
You should check that last line before using it because the alterordeletedependants is something I now use in my c# program, I don't remember if it worked in powershell.
Good luck!