VBS - Find SCCM Collection Id's, Names and Package Names a computer is apart of? - vbscript

Currently I have 'excel SQL query' for subject requirement and it is executing fine without any issues.
Current Excel SQL query Script: I have created SQL query which is connect to SCCM server and get the below details.
Excel 2013/2016-> Data -> Connections-> Workbook Connections->
Excel SQL Query
Connection String:
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=CM_CAS;Data Source=<SCCMServerIP>;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=<SCCMServerHostName>;Use Encryption for Data=False;Tag with column collation when possible=False
Command Type: SQL
Command Text:
DECLARE #machname varchar(max)
SET #machname = '<DeviceHostName>'
select CollectionID,CollectionName,packagename,#machname as MachineName from v_AdvertisementInfo
-- select AssignmentID,AssignmentName,CollectionID,CollectionName,ApplicationName,AppModelID from v_ApplicationAssignment
where CollectionID in
(select FCM.CollectionId from dbo.v_R_System r join
dbo.v_FullCollectionMembership FCM on R.ResourceID = FCM.ResourceID join
dbo.v_Collection C on C.CollectionID = FCM.CollectionID Where R.Name0
= #machname) and
ProgramName not like '%Remove%'and
ProgramName not like '%Un-Install%'and
CollectionName not like '%Test%' and
CollectionName not like '%temp%'
union
select CollectionID,CollectionName,ApplicationName,#machname as MachineName from v_ApplicationAssignment
where CollectionID in
(select FCM.CollectionId from dbo.v_R_System r join
dbo.v_FullCollectionMembership FCM on R.ResourceID = FCM.ResourceID join
dbo.v_Collection C on C.CollectionID = FCM.CollectionID Where R.Name0
= #machname) and
CollectionName not like '%Test%' and
CollectionName not like '%temp%'
+++++++++++++++++++++++++++++++++++++++++++++
And example Excel output will be as below for
hostname 'IN-00001236'
Result/Output
Requirement is : for Laptop EOL refresh
Gather all collection id's which is member of IN-00001236 (EOL Device) and add new device host name (IN-1111) into result collection id's! then delete IN-00001236 from SCCM. Generate report in excel/CSV?
I have a challenge In above Excel SQL Query? like I have add/replace hostname every time/run under 'Command Text'
So, I need to automate this complete process using VBS or PS?

If I understand you correctly you want a new record to have all memberships of the old record.
In my opinion you can focus only on collection memberships, whether the deployment to a collection is a package, application or update should not be important as long as the collections are the same.
So first you would need to translate your devices name to a resourceid as those are the primary key in all sccm tables:
$WS = 'IN-00001236'
$resourceID = (Get-WmiObject -Class "SMS_R_System" -Filter "(Name = '$WS')" | Select-Object -last 1).ResourceID
once you have that you can get all the collection members
$collectionMembers = (Get-WmiObject -Class "SMS_FullCollectionMembership" -Filter "(ResourceID = '$resourceID')" | where { $_.IsDirect -eq $true }).CollectionID
to delete a record use this
[void](Get-WmiObject -Class "SMS_R_System" -Filter "(ResourceID = '$resourceID')").Delete()
now you have to add those to the new record (first get resourceID again)
Foreach($CollID in $collectionMembers) {
$CollectionQuery = Get-WmiObject -Class "SMS_Collection" -Filter "CollectionID = '$CollID'"
$directRule = (Get-WmiObject -List -Class "SMS_CollectionRuleDirect").CreateInstance()
$directRule.ResourceClassName = "SMS_R_System"
$directRule.ResourceID = $newResourceID
[void]$CollectionQuery.AddMemberShipRule($directRule)
}
If you want to use this for multiple devices in a loop you can just create a csv file with oldrecord,newrecord
import with
$records = Import-Csv <path to csv> -Header old,new
and then use a loop outside all the code like
foreach ($record in $records) {
# inside here use $record.old or $record.new for the old/new names like
# $WS = $record.old
}
Now i don't know if you even would need the excel file anymore if you just have a script doing the work, but in case you really do you can create a excel readable csv from powershell with export-csv (might need options like -Delimiter ';' -NoTypeInformation -Encoding UTF8 to be easily readable)
In theory you can execute your whole sql query in powershell as well
$sqlText = "your query"
$SQLConnection = new-object System.Data.SqlClient.SQLConnection("Server=<sccmserver>;Database=<sccm db>;Integrated Security=SSPI")
$SQLConnection.Open();
$cmd = new-object System.Data.SqlClient.SqlCommand($sqlText, $SQLConnection);
$reader = $cmd.ExecuteReader()
while ($reader.Read()) {
$reader["<columnname>"]
}
and recreate your file in the ps script

Finally I completed VBS as below. it's working fine.
Dim connect, sql, resultSet, pth, txt
Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set connect = CreateObject("ADODB.Connection")
connect.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=CM_CAS;Data Source=<SCCMServerIP>;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=<SCCMServerHostName>;Use Encryption for Data=False;Tag with column collation when possible=False;Trusted_Connection=True;"
connect.Open
sql="select CollectionID,CollectionName,packagename,<HostName> as MachineName from v_AdvertisementInfo where CollectionID in (select FCM.CollectionId from dbo.v_R_System r join dbo.v_FullCollectionMembership FCM on R.ResourceID = FCM.ResourceID join dbo.v_Collection C on C.CollectionID = FCM.CollectionID Where R.Name0 = 'HostName') and ProgramName not like '%Remove%'and ProgramName not like '%Un-Install%'and CollectionName not like '%Test%' and CollectionName not like '%temp%' union select CollectionID,CollectionName,ApplicationName,#machname as MachineName from v_ApplicationAssignment where CollectionID in (select FCM.CollectionId from dbo.v_R_System r join dbo.v_FullCollectionMembership FCM on R.ResourceID = FCM.ResourceID join dbo.v_Collection C on C.CollectionID = FCM.CollectionID Where R.Name0 = 'HostName') and CollectionName not like '%Test%' and CollectionName not like '%temp%'"
Set resultSet = connect.Execute(sql)
pth = "C:\test\test.csv"
Set txt = ObjFSO.CreateTextFile(pth, True)
On Error Resume Next
resultSet.MoveFirst
Do While Not resultSet.eof
txt.WriteLine(resultSet(0) & "," & resultSet(1) & "," & resultSet(2))
resultSet.MoveNext
Loop
resultSet.Close
connect.Close
Set connect = Nothing

Related

How can i write a string/query to a hive query file in cmd?

i have ran the below so i can write this to a file settings.hql
"SET schema = products;SET company = amazon;SET tablename = test;" > settings.hql
in cmd.
but it does not work i get:
SET schema = products;SET company = amazon;SET tablename = test;: command not found
Use echo command:
C:\Users\leftjoin>echo SET schema = products;SETcompany = amazon;SET tablename = test; > settings.hql
C:\Users\leftjoin>type settings.hql
SET schema = products;SETcompany = amazon;SET tablename = test;
If you are using Microsoft Windows cmd.exe as your tag implies, you need to use ECHO.
ECHO>"settings.hql" SET schema = products;SET company = amazon;SET tablename = test;

How to change the loop Powershell content from the csv file automatically?

I want to change the loop PowerShell content from the CSV file automatically, is there someone know how to achieve the goal?
I want to run the loop PowerShell as below,I export the AD Group Members UPN with CSV file like One#contoso.com. I want to change the Userlist with the UPN automatically because there have more than 1000 members in the group and I have to change the upn from one#contoso.com to 'one#contoso.com',it’s easy to make a miss, is there has a smart way can achieve the goal,thanks.
Export-ADGroupmember UPN:
Get-ADGroupmember -identity adgroup | % { get-aduser $_.samaccountname | select userprincipalname } | export-csv upn.csv -notypeinformation
Loop PowerShell:
Loop PowerShell:
$UserList = #(
'One#contoso.com'
'Two#contoso.com'
'Three#contoso.com'
'Four#contoso.com'
'Five#contoso.com'
)
foreach ($UL_Item in $UserList)
{
$ARAGU_Params = #{
TenantName = "contoso"
HostPoolName = "contosoHostPool"
AppGroupName = "Desktop Application Group"
UserPrincipalName = $UL_Item
}
Add-RdsAppGroupUser #ARAGU_Params
}
You cant change content in your $UserList .More precisely, it is possible but affect the performance since You will need to read from the file and break it into segments. The best way is to download all users at once.You can do it like this:
$UserList=Get-ADGroupmember -identity adgroup | % { get-aduser $_.samaccountname | select userprincipalname }
foreach ($UL_Item in $UserList)
{
$ARAGU_Params = #{
TenantName = "contoso"
HostPoolName = "contosoHostPool"
AppGroupName = "Desktop Application Group"
UserPrincipalName = $UL_Item.userprincipalname
}
Add-RdsAppGroupUser #ARAGU_Params
}

Powershell - How to export to CSV file a query with Oracle Data Provider for .NET (ODP.NET)

In Powershell, I want to export the results of a query ODP.NET to a CSV file
This is my code:
$connection = New-Object Oracle.ManagedDataAccess.Client.OracleConnection($connectionString)
$connection.open()
$cmd = New-Object Oracle.ManagedDataAccess.Client.OracleCommand -ArgumentList $query
$cmd.Connection = $connection
$reader = $cmd.ExecuteReader()
This code is working with the correct values of $connectionString and $query variables. If I add this code I can read the correct result of my query:
while ($reader.Read()) {
$col1 = $reader["Col1"]
$col2 = $reader["Col2"]
$col3 = $reader["Col3"]
#Write-Host $col1, $col2, $col3
}
Those 3 columns are an example, in my real case I have many more. Then I want to export directly to a CSV file, something like this:
XXXXXXX | export-csv -Delimiter ";" -Path "E:\export.csv"
How can I do this? The expected result is a CSV file similar than this:
"4581";"6";26867;"191057";"BH02 - 26867 - ";"30/05/2019";"";"2040";1991,04;"2040";2,4;"00";"";348;"";"1";"1";"";"";"BRL";2040;"";1
"4581";"4";28313;"747990";"BH02 - 28313 - ";"30/05/2019";"";"140";137,13;"140";2,05;"00";"";459;"";"1";"1";"";"";"BRL";140;"";1
"4581";"1";28316;"881411";"BH02 - 28316 - ";"30/05/2019";"";"140";137,13;"140";2,05;"00";"";460;"";"1";"1";"";"";"BRL";140;"";1
"4581";"1";;"878676";"BH02 - - 275650/PF19";"28/05/2019";"";"103";100,8885;"103";2,05;"00";"";305;"";"1";"1";"";"";"BRL";103;"";1
"4581";"6";28168;"006778";"BH02 - 28168 - 275714/PF19";"30/05/2019";"";"848";828,92;"848";2,25;"00";"";429;"";"1";"1";"";"";"BRL";848;"";1
"4581";"3";29080;"641559";"BH02 - 29080 - ";"30/05/2019";"";"3424,14";3338,5365;"3424,14";2,5;"00";"";488;"";"1";"1";"";"";"BRL";3424,14;"";1
"4581";"4";;"602483";"BH02 - - 23443";"28/05/2019";"";"157";153,7815;"157";2,05;"00";"";329;"";"1";"1";"";"";"BRL";157;"";1
What is the raw output of this Oracle command?
If it is a list, then use -Join and use the Csv cmdlets to export to convert to a csv file.
This also would indicate that you are new or never used PowerShell before since csv use case is a daily thing. That's OK, but jump on YouTube, MSDN Channel9 and go through the videos on PowerShell, beginning/intermediate/advanced, PowerShell and Databases, PowerShell and Csv files and get ramped up to limit/avoid, misconceptions, frustrations, bad habits, etc.
It should be straightforward as doing something like this ( of course don't put passwords in scripts)...
Add-Type -Path 'C:\oracle\instantclient_10_2\odp.net\managed\common\Oracle.ManagedDataAccess.dll'
$username = "USERID"
$password = "Password"
$datasource = "HOST:PORT/Instance"
$connectionString = "User Id = $username;Password = $password;Data Source = $datasource"
$query = "SELECT DATA1, DATA2, DATA3, DATA4, DATA5, DATA6, DATA7, DATA8
FROM TABLE WHERE NOT REGEXP_LIKE (EMAIL_ID, '#domain.com','i') order by DATA2"
$connection = New-Object Oracle.ManagedDataAccess.Client.OracleConnection("$connectionString")
$connection.open()
$command = New-Object Oracle.ManagedDataAccess.Client.OracleCommand
$command.Connection = $connection
$command.CommandText = $query
$ds = New-Object system.Data.DataSet
$da = New-Object Oracle.ManagedDataAccess.Client.OracleDataAdapter($command)
[void]$da.fill($ds)
return $ds.Tables[0] |
SELECT DATA1, DATA2, DATA3, DATA4, DATA5, DATA6, DATA7, DATA8 |
Export-CSV "C:\test.csv" -NoTypeInformation
$connection.Close()

Powershell and Oracle, exporting SQL data to csv

I have an Oracle SQL table that contains email addresses. I need to extract this data and insert it into an array, and export to a csv file. I'm not too sure where to go from here. My code so far is:
$odpAssemblyName = "Oracle.DataAccess, Version=2.112.3.0,
Culture=neutral, PublicKeyToken=89b483f429c47342"
[System.Reflection.Assembly]::Load($odpAssemblyName)
$con = New-Object Oracle.DataAccess.Client.OracleConnection("User Id=HR;Password=oracle;Data Source=XE")
$cmd=$con.CreateCommand()
$cmd.CommandText= #"
SELECT DISTINCT email FROM
hr.emails WHERE acct_enabled = 'Y'
AND UPPER(email) NOT LIKE 'AIS%'ORDER BY email
"#
$con.Open()
$rdr=$cmd.ExecuteReader()
$columnNames=$rdr.GetSchemaTable() | Select-Object -ExpandProperty ColumnName
$resultSet=#()
while ($rdr.Read()) {
$intData=$rdr.GetOracleString(0)
"{0,0}" -f $intData.Value
}
$con.Close()
Can anybody help me with my While loop (I'm new to programming mostly) and help me add the result set to an array, and export the result set to a nice little csv file?
Thanks in advance for any help/pointers
James
Try something like this, although I cant exactly test it based on no oracle DB available on my side.
$odpAssemblyName = "Oracle.DataAccess, Version=2.112.3.0,
Culture=neutral, PublicKeyToken=89b483f429c47342"
[System.Reflection.Assembly]::Load($odpAssemblyName)
$con = New-Object Oracle.DataAccess.Client.OracleConnection("User Id=HR;Password=oracle;Data Source=XE")
$cmd=$con.CreateCommand()
$cmd.CommandText= #"
SELECT DISTINCT email FROM
hr.emails WHERE acct_enabled = 'Y'
AND UPPER(email) NOT LIKE 'AIS%'ORDER BY email
"#
$con.Open()
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $cmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$emaillist = $DataSet.Tables[0].Email
$con.Close()
$emaillist | Export-csv "C:\Somefolder\OracleEmails.csv" -NoTypeInformation

formatting csv files and powershell

Ok so we have a manual process that runs through PL/SQL Developer to run a query and then export to csv.
I am trying to automate that process using powershell since we are working in a windows environment.
I have created two files that seems to be exact duplicates from the automated and manual process but they don't work the same so I assume I am missing some hidden characters but I can't find them or figure out how to remove them.
The most obvious example of them working differently is opening them in excel. The manual file opens in excel automatically putting each column in it's own seperate column. The automated file instead puts everything into one column.
Can anybody shed some light? I am hoping that by resolving this or at least getting some info will help with the bigger problem of it not processing correctly.
Thanks.
ex one column
"rownum","year","month","batch","facility","transfer_facility","trans_dt","meter","ticket","trans_product","trans","shipper","customer","supplier","broker","origin","destination","quantity"
ex seperate column
"","ROWNUM","RPT_YR","RPT_MO","BATCH_NBR","FACILITY_CD","TRANSFER_FACILITY_CD","TRANS_DT","METER_NBR","TKT_NBR","TRANS_PRODUCT_CD","TRANS_CD","SHIPPER_CD","CUSTOMER_NBR","SUPPLIER_NBR","BROKER_CD","ORIGIN_CD","DESTINATION_CD","NET_QTY"
$connectionstring = "Data Source=database;User Id=user;Password=password"
$connection = New-Object System.Data.OracleClient.OracleConnection($connectionstring)
$command = New-Object System.Data.OracleClient.OracleCommand($query, $connection)
$connection.Open()
Write-Host -ForegroundColor Black " Opening Oracle Connection"
Start-Sleep -Seconds 2
#Getting data from oracle
Write-Host
Write-Host -ForegroundColor Black "Getting data from Oracle"
$Oracle_data=$command.ExecuteReader()
Start-Sleep -Seconds 2
if ($Oracle_data.read()){
Write-Host -ForegroundColor Green "Connection Success"
while ($Oracle_data.read()) {
#Variables for recordset
$rownum = $Oracle_data.GetDecimal(0)
$rpt_yr = $Oracle_data.GetDecimal(1)
$rpt_mo = $Oracle_data.GetDecimal(2)
$batch_nbr = $Oracle_data.GetString(3)
$facility_cd = $Oracle_data.GetString(4)
$transfer_facility_cd = $Oracle_data.GetString(5)
$trans_dt = $Oracle_data.GetDateTime(6)
$meter_nbr = $Oracle_data.GetString(7)
$tkt_nbr = $Oracle_data.GetString(8)
$trans_product_cd = $Oracle_data.GetString(9)
$trans_cd = $Oracle_data.GetString(10)
$shipper_cd = $Oracle_data.GetString(11)
$customer_nbr = $Oracle_data.GetString(12)
$supplier_nbr = $Oracle_data.GetString(13)
$broker_cd = $Oracle_data.GetString(14)
$origin_cd = $Oracle_data.GetString(15)
$destination_cd = $Oracle_data.GetString(16)
$net_qty = $Oracle_data.GetDecimal(17)
#Define new file
$filename = "Pipeline" #Get-Date -UFormat "%b%Y"
$filename = $filename + ".csv"
$fileLocation = $newdir + "\" + $filename
$fileExists = Test-Path $fileLocation
#Create object to hold record
$obj = new-object psobject -prop #{
rownum = $rownum
year = $rpt_yr
month = $rpt_mo
batch = $batch_nbr
facility = $facility_cd
transfer_facility = $transfer_facility_cd
trans_dt = $trans_dt
meter = $meter_nbr
ticket = $tkt_nbr
trans_product = $trans_product_cd
trans = $trans_cd
shipper = $shipper_cd
customer = $customer_nbr
supplier = $supplier_nbr
broker = $broker_cd
origin = $origin_cd
destination = $destination_cd
quantity = $net_qty
}
$records += $obj
}
}else {
Write-Host -ForegroundColor Red " Connection Failed"
}
#Write records to file with headers
$records | Select-Object rownum,year,month,batch,facility,transfer_facility,trans_dt,meter,ticket,trans_product,trans,shipper,customer,supplier,broker,origin,destination,quantity |
ConvertTo-Csv |
Select -Skip 1|
Out-File $fileLocation
Why are you skipping the first row(usually the headers)? Also, try using Export-CSV instead:
#Write records to file with headers
$records | Select-Object rownum, year, month, batch, facility, transfer_facility, trans_dt, meter, ticket, trans_product, trans, shipper, customer, supplier, broker, origin, destination, quantity |
Export-Csv $fileLocation -NoTypeInformation

Resources