Wont move past first while statement - powershell

I have been asked to change the script once again and when doing so I have ran into an issue with the script.
I have broken down the sections on the script into different sections so you can better see what i am trying to do. I am trying to choose between the TC, MonsterLock, and Cyc and have them do their own functions when i choose one of them.
The problem I am having is that once I choose one of them I can enter the next section and enter in the information for DATABASE1, DATABASE2,DATABASE3, and DATABASE4. But when I do so it loops at that section and constantly asks me
This script sets up DATABASE Staging
Sets up location you want to run staging
Sets up location you want to run staging
Sets up location you want to run staging
Sets up location you want to run staging
This happens everytime I choose tc, MonsterLock, or Cyc. I have information in the MonsterLock as you can see but it doesnt moce past the loop and start the commands that are located inside.
write-host "This script sets up DATABASE Staging"
$ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(TC/MonsterLock/Cyc)"
While($ProductionDistro -notmatch "(TC|MonsterLock|Cyc)"){
write-host "You have entered an error" -ForegroundColor Red
write-host "You must type TC or MonsterLock or Cyc"
write-host "you typed $ProductionDistro"
write-host "This script sets up DATABASE Staging"
$ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to ru(TC/MonsterLock/Cyc)"
}
while($ProductionDistro -match $TC) {
write-host "Sets up location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
write-host "you have enterd an error" -ForegroundColor Red
write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
write-host "you typed $ElementDistro"
write-host "set location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
}
this is the first while statemet
While($PrductionDistro -match $MonsterLock){
write-host "Sets up location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
write-host "you have enterd an error" -ForegroundColor Red
write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
write-host "you typed $ElementDistro"
write-host "set location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
}
}
while( $ElementDistro -match $DATABASE1 ){
function Execute-MySqlcommand {param( [string]$Server, #the host of the SQL server
[string]$Database1, #the name of the database
[System.Data.MySqlclient.MySqlcommand]$Command) #the command to execute (name of stored command)
$mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
$MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE1.DATABASE1S2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE1.DATABASE1S3.BTXSUPB"
$MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE1.DATABASE1S2.BTXADDR;TRUNCATE TABLE DATABASE1.DATABASE1S3.BTXSUPB; INSERT INTO DATABASE1.DATABASE1S3.BTXSUPB SELECT * FROM DATABASE1.DATABASE1S2.BTXSUPB; select count(*) from DATABASE1.DATABASE.BTXADDR; select count(*) from DATABASE1S.DATABASE.BTXADDR; select count(*) from DATABASE1.DATABASE.BTXSURB; select count(*) from DATABASE1S.DATABASE.BTXSUPB;"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $mysqlConnection
$mysqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$mysqlConnection.Close()
if ($Result -gt 0) {return $True} else {return $False}
}
function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
[string]$DATABASE1, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE1;Description=DATABASE1;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE1;DATASET=DEFAULT"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
function Copy-File {
#.Synopsis
# Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
param}($DATABASE0980453.pkg,"d/DATABASE1/code_stg")
# create destination if it's not there ...
#mkdir $destination -force -erroraction SilentlyContinue
foreach($original in ls $source -recurse) {
$result = $original.FullName.Replace($source,$destination)
while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
if($original.PSIsContainer) {
# mkdir $result -ErrorAction SilentlyContinue
# } else {
copy $original.FullName -destination $result
}
cd /d/DATABASE1/code_stg
install ../DATABASE0980453.pkg
}
while($ElementDistro -match $DATABASE2 ) {
function execute-MySqlcommand {param( [string]$Server, #the host of the SQL server
[string]$DataBase2, #the name of the database
[System.Data.MySqlclient.MySqlcommand]$Command) #the command to execute (name of stored command)
$mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
$MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE2.DATABASE2MS2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE2.DATABASE2S3.BTXSUPB"
$MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE2.DATABASE2S2.BTXADDR;TRUNCATE TABLE DATABASE2.DATABASE2S3.BTXSUPB; INSERT INTO DATABASE2.DATABASE2S3.BTXSUPB SELECT * FROM DATABASE2.DATABASE2S2.BTXSUPB; select count(*) from DATABASE2.DATABASE.BTXADDR; select count(*) from DATABASE2S.DATABASE.BTXADDR; select count(*) from DATABASE2.DATABASE.BTXSURB; select count(*) from DATABASE2S.DATABASE.BTXSUPB;"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $mysqlConnection
$mysqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$mysqlConnection.Close()
if ($Result -gt 0) {return $True} else {return $False}
}
function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
[string]$DATABASE2, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE2; Description=DATABASE2; Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE2;"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
function Copy-File {
#.Synopsis
# Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
param}($DATABASE0980453.pkg,"d/DATABASE2/code_stg")
# create destination if it's not there ...
#mkdir $destination -force -erroraction SilentlyContinue
foreach($original in ls $source -recurse) {
$result = $original.FullName.Replace($source,$destination)
while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
if($original.PSIsContainer) {
# mkdir $result -ErrorAction SilentlyContinue
# } else {
copy $original.FullName -destination $result
}
cd /d/DATABASE2/code_stg
install ../DATABASE0980453.pkg
}
While( $ElementDistro -match $DATABASE3 ) {
function Execute-MySqlcommand {param( [string]$Server, #the host of the SQL server
[string]$DATABASE3, #the name of the database
[System.Data.MySqlclient.MySqlcommand]$Command) #the command to execute (name of stored command)
$mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
$MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE3.DATABASE3S2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE3.DATABASE3S3.BTXSUPB"
$MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE3.DATABASE3S2.BTXADDR;TRUNCATE TABLE DATABASE3.DATABASE3S3.BTXSUPB; INSERT INTO DATABASE3.DATABASE3S3.BTXSUPB SELECT * FROM DATABASE3.DATABASE3S2.BTXSUPB; select count(*) from DATABASE3.DATABASE.BTXADDR; select count(*) from DATABASE3S.DATABASE.BTXADDR; select count(*) from DATABASE3.DATABASE.BTXSURB; select count(*) from DATABASE3S.DATABASE.BTXSUPB;"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $mysqlConnection
$mysqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$mysqlConnection.Close()
if ($Result -gt 0) {return $True} else {return $False}
}
function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
[string]$DATABASE3, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE3;Description=DATABASE3;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE3;"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
cd /d/DATABASE3/code_stg
install ../DATABASE0980453.pkg
}
function Copy-File {
#.Synopsis
# Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
param}($DATABASE0980453.pkg,"d/DATABASE3/code_stg")
# create destination if it's not there ...
#mkdir $destination -force -erroraction SilentlyContinue
foreach($original in ls $source -recurse) {
$result = $original.FullName.Replace($source,$destination)
while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
if($original.PSIsContainer) {
# mkdir $result -ErrorAction SilentlyContinue
# } else {
copy $original.FullName -destination $result
}
While($ElementDistro -match $DATABASE4 ) {
function Execute-MySqlcommand {param( [string]$Server, #the host of the SQL server
[string]$DATABASE4, #the name of the database
[System.Data.MySqlclient.MySqlcommand]$Command) #the command to execute (name of stored command)
$mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
$MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE4.DATABASE42.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE4.DATABASE4S3.BTXSUPB"
$MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE4.DATABASE4S2.BTXADDR;TRUNCATE TABLE DATABASE4.DATABASE4S3.BTXSUPB; INSERT INTO DATABASE4.DATABASE4S3.BTXSUPB SELECT * FROM DATABASE4.DATABASE4S2.BTXSUPB; select count(*) from DATABASE4.DATABASE.BTXADDR; select count(*) from DATABASE4S.DATABASE.BTXADDR; select count(*) from DATABASE4.DATABASE.BTXSURB; select count(*) from DATABASE4S.DATABASE.BTXSUPB;"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $mysqlConnection
$mysqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$mysqlConnection.Close()
if ($Result -gt 0) {return $True} else {return $False}
}
function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
[string]$DATABASE4, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE4;Description=DATABASE4;Trusted_Connection=Yes;WSID=Server;DATABASE=TF90PVS;"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
function Copy-File {
#.Synopsis
# Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
param}($DATABASE0980453.pkg,,"d/DATABASE4/code_stg")
# create destination if it's not there ...
#mkdir $destination -force -erroraction SilentlyContinue
foreach($original in ls $source -recurse) {
$result = $original.FullName.Replace($source,$destination)
while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
if($original.PSIsContainer) {
# mkdir $result -ErrorAction SilentlyContinue
# } else {
copy $original.FullName -destination $result
}
cd /d/DATABASE4/code_st
install ../DATABASE0980453.pkg
}
While($ElementDistro -match $ALL ){
function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
[string]$DATABASE1,$DATABASE2,$DATABASE3,$DATABASE4, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "(DATABASE_CONNECT_STRING=DSN=DATABASE1;Description=DATABASE1;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE1;DATASET=DEFAULT;),(DATABASE_CONNECT_STRING=DSN=DATABASE2; Description=DATABASE2; Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE2;),(DATABASE_CONNECT_STRING=DSN=DATABASE3;Description=DATABASE3;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE3;),(DATABASE_CONNECT_STRING=DSN=DATABASE4;Description=DATABASE4;Trusted_Connection=Yes;WSID=Server;DATABASE=TF90PVS;)"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
install ../DATABASE0980453.pkg
}
Second While statement
While($ProductionDistro -match $Cyc) {
write-host "Sets up location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
write-host "you have enterd an error" -ForgroundColor Red
write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
write-host "you typed $ElementDistro"
write-host "set location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
}
}
}}}}}

The loop beginning while($ProductionDistro -match $TC) { does not appear to modify $ProductionDistro so once you get into that loop it will go round forever. The same appears to apply to the other while($ProductionDistro... loops.
For a while loop to terminate you must update some of the values used in the condition to make the condition no longer evaluate to something true.

Related

Loop PS from specific line

I have this script:
Can I add a loop ; after I Enter ID & IP and add in 'db.csv' go back to ask again $inputID and a loop for ask if typed ID or IP is good (?)
I need 2 'loops' in this script first loop for the confirmation typed if info is good or not >> if not go back to add again ;; and second loop after I add ID, IP and script write in csv new ID go again in top of script where need to $inputID for type newest ID which added previous.
#### START SCRIPT #####
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$dbfile = "C:\test.csv"
$db = [System.Collections.Generic.List[object]]::new()
if (Test-Path -Path $dbfile -PathType Leaf) { $db.AddRange((Import-Csv -Path $dbfile)) }
$dbUpdated = $false
while ($true) {
While ( ($Null -eq $inputID) -or ($inputID -eq '') ) {
$inputID = Read-Host -Prompt "Introduceti ID sau Tastati 'Q' for exit"
}
if ($inputID -eq 'q') { break }
$entry = $db | Where-Object { $_.HostName -eq $inputID }
if ($entry) {
Write-Host "$inputID Ok!" -ForegroundColor Green
continue
}
Write-Host "$inputID nu exista in baza de date!" -ForegroundColor Red
# ask for confirmation
$title = 'Adaugare ID nou?'
$question = 'Doriti sa introduceti un ID nou in Baza de Date?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -ne 0) {
continue
}
do {
$IP = Read-Host -Prompt "Introduceti IP pentru: $inputID"
} while (![IPAddress]::TryParse($IP, [ref]$null))
$db.Add([PsCustomObject]#{ HostName = $inputID; IP = $IP })
Write-Host "Data : $inputID,$IP adaugat cu succes in baza de date!"
$dbUpdated = $true
}
if ($dbUpdated) {
$db | Export-Csv -Path $dbfile -NoTypeInformation -Force
$dbTrimmer = Get-Content $dbfile
$dbTrimmer.Replace('","', ",").TrimStart('"').TrimEnd('"') | Set-Content -Path $dbfile -Force -Confirm:$false
}
# Script continue. If put correct ID run the script below if not Ask if want to add new ID after that return to ask ID (of course here I typed new ID which I enter before in db) and run the script for that ID.
I would do this inside one endless while {..} loop where another do{..} while() is used for the second question about the IP.
Also, you can do all from memory and only write the data to file after the user quits the while loop (and only if an update was made)
Something like this:
$dbfile = "C:\test.csv"
# create a List object to store and update the data in memory
$db = [System.Collections.Generic.List[object]]::new()
# if the file can be found, import the data and add to the $db List
if (Test-Path -Path $dbfile -PathType Leaf) { $db.AddRange((Import-Csv -Path $dbfile)) }
# create a flag to check later if an new entry was made
$dbUpdated = $false
# enter an endless loop
while ($true) {
$inputID = Read-Host -Prompt "Introduceti ID. Type 'Q' to exit"
# break the loop if the user wants to stop
if ($inputID -eq 'q') { break }
# test if the id is already in the $db collection
$entry = $db | Where-Object { $_.HostName -eq $inputID }
if ($entry) {
Write-Host "$inputID Ok!" -ForegroundColor Green
continue # go back to asking for a new ID
}
Write-Host "$inputID nu exista in baza de date!" -ForegroundColor Red
# ask for confirmation
$title = 'Add New ID?'
$question = 'Doriti sa introduceti un ID nou in Baza de Date?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -ne 0) {
continue # go back to asking for a new ID
}
# ask for IP for this new entry
do {
$IP = Read-Host -Prompt "Introduceti IP for $inputID"
} while ([string]::IsNullOrWhiteSpace($IP))
# you may want to change the 'while' condition above to
# while (![IPAddress]::TryParse($IP, [ref]$null))
# to ensure a valid IP address is entered.
# add the given ID and IP to the $db collection in memory
$db.Add([PsCustomObject]#{ HostName = $inputID; IP = $IP })
Write-Host "Data : $inputID,$IP adaugat cu succes in baza de date!"
$dbUpdated = $true
}
# here we can test if new entries have been added
if ($dbUpdated) {
# overwrite the file with the updated info
$db | Export-Csv -Path $dbfile -NoTypeInformation -Force
# Apparently you don't want quotes in the CSV file, and in this case it would be safe enough to do
$dbTrimmer = Get-Content $dbfile
$dbTrimmer.Replace('","', ",").TrimStart('"').TrimEnd('"') | Set-Content -Path $dbfile -Force -Confirm:$false
# but please be VERY careful with that because in other csv files, the fields may contain
# Newlines, the delimiter character itself or quotes and if that is the case, the csv file
# will become unusable..
# See https://stackoverflow.com/a/69705776/9898643 to do that safely.
}

Opening a SSRS project using Powershell

I have a report that is copied to a number of different servers. It is imported manually and the data source properties are altered to match the current server's specs. I would like to be able to automate the process by enabling users to open a the SSRS report and dynamically alter it's shared data source properties through PowerShell. I hope you could help. You may see reference below.
The script would accept an input parameter for servername, username and password. Also, the save my password must be ticked.
I couldn't believe I managed to create a script for this. You may make use of the script below as future reference. Comments are available for each part and anything that needs to be altered has a "here" keyword , ex. Your_database_name_here .
Import-Module SqlPs
#Input parameter to get Server\Instancename of your Datasource
$Servername = Read-Host "Please enter your Servername"
$Instancename = Read-Host "Please enter your Instancename. For default instance please press enter"
Write-host ""
if ($Instancename -eq ""){
$ServerInstance = $Servername
}
Else {
$ServerInstance = $Servername +"\"+ $InstanceName
}
#Setting up SSRS Target URL. This is the location where your reports would be deployed.
if ($Instancename -eq ""){
$ReportServerUri = "http://$Servername/ReportServer//ReportService2010.asmx?wsdl"
$TargetURL = "http://$Servername/Reports"
}
Else {
$ReportServerUri = "http://$Servername/ReportServer_$Instancename//ReportService2010.asmx?wsdl"
$TargetURL = "http://$Servername/Reports_$Instancename"
}
$global:proxy = New-WebServiceProxy -Uri $ReportServerUri -UseDefaultCreden
#We would make use of SQL Server Authentication for the reports shared datasource so you need to supply a username and password.
Write-Host " SQL Server Authentication:"
$Username = Read-Host " Username"
$Password = Read-Host -AsSecureString "Password"
$type = $Proxy.GetType().Namespace
$datatype = ($type + '.Property')
$property =New-Object ($datatype);
$property.Name = “NewFolder”
$property.Value = “NewFolder”
$numproperties = 1
$properties = New-Object ($datatype + '[]')$numproperties
$properties[0] = $property;
$newFolder = $proxy.CreateFolder("Reports”, “/”, $properties);
$newFolder = $proxy.CreateFolder("Data Sources”, “/”, $properties);
$Children =$proxy.ListChildren("/",$false)
$DBname = 'Your_Database_Name_Here'
# Creating Datasource through powershell
Write-Host " Creating Datasource ..."
$Name = "Name_Your_Datasource_here"
$Parent = "/Data Sources"
$ConnectString = "data source=$Servername\$Instancename;initial catalog=$DBname"
$type = $Proxy.GetType().Namespace
$DSDdatatype = ($type + '.DataSourceDefinition')
$DSD = new-object ($DSDdatatype)
if($DSD -eq $null){
Write-Error Failed to create data source definition object
}
$CredentialDataType = ($type + '.CredentialRetrievalEnum')
$Cred = new-object ($CredentialDataType)
$CredEnum = ($CredentialDataType).Integrated
$Cred.value__=1
$DSD.CredentialRetrieval =$Cred
$DSD.ConnectString = $ConnectString
$DSD.Enabled = $true
$DSD.EnabledSpecified = $false
$DSD.Extension = "SQL"
$DSD.ImpersonateUserSpecified = $false
$DSD.Prompt = $null
$DSD.WindowsCredentials = $false
$DSD.UserName = $Username
$DSD.Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
$newDSD = $proxy.CreateDataSource($Name,$Parent,$true,$DSD,$null)
#Deploying RLD files to Target URL
Write-Host " Deploying RDL files ..."
$stream = Get-Content 'D:\Your_RDL_path_here.rdl' -Encoding byte
$warnings =#();
$proxy.CreateCatalogItem("Report","Report_Name_here","/Reports",$true,$stream,$null,[ref]$warnings)
#Let's make use of the datasource we just created for your RDL files.
$Items = $global:proxy.listchildren("/Data Sources", $true)
foreach ($item in $items)
{
$DatasourceName = $item.Name
$DatasourcePath = $item.Path
}
$RDLS = $global:proxy.listchildren("/Reports", $true)
foreach ($rdl in $rdls)
{
$report = $rdl.path
$rep = $global:proxy.GetItemDataSources($report)
$rep | ForEach-Object {
$proxyNamespace = $_.GetType().Namespace
$constDatasource = New-Object ("$proxyNamespace.DataSource")
$constDatasource.Name = $DataSourceName
$constDatasource.Item = New-Object ("$proxyNamespace.DataSourceReference")
$constDatasource.Item.Reference = $DataSourcePath
$_.item = $constDatasource.Item
$global:proxy.SetItemDataSources($report, $_)
Write-Host "Changing datasource `"$($_.Name)`" to $($_.Item.Reference)"
}
}
#Open a IE browser to view the report.
$IE=new-object -com internetexplorer.application
$IE.navigate2($TargetURL)
$IE.visible=$true
Write-Host ""
Write-Host "You may now view the Reports through the open IE browser."
Write-Host -ForegroundColor Green "**STEP COMPLETED!"

Powershell workflow/parallel citrix sessions

Edit - I should preface this by saying I'm very new to powershell. This is one of the first "complicated" scripts i've tried to write.
I'm trying to use workflow/parallel to run a script against two lists simultaneously. after I get it working, the goal will be to add multiple lists, to cut down on the time it takes to process each one.
The script by itself works great. Adding the workflow returns nothing. :/
$Global:ctxsession = Read-Host -Prompt 'Input the Username'
$serverlist1 = get-content .\serverlist1.txt
$serverlist2 = get-content .\serverlist2.txt
function citrixlist {
#([string]$Servers)
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$servers
)
foreach ($server in $servers) {
#ping first
if (Test-Connection -count 1 -computer $server -quiet) {
#temporary write-host to see where it hangs (might leave in permanently)
Write-Host $server
#check for sessions
$sessions = qwinsta /server $server| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
#separating into objects
$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
$item.Active = $_.Substring(0,1) -match '>'
$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item.Type = $_.Substring(56,12).Trim()
$item.Device = $_.Substring(68).Trim()
$item
}
foreach ($session in $sessions){
#match for session name entered
if ($session.Username -match $ctxsession){
Write-Host 'Found' $session.Username 'on' $server 'with Session ID' $session.Id $session.State
#Kill session with ID and Server, with verbose switch
#rwinsta $session.Id /server:$server /v
}
}
}
}
}
workflow get-citrixlist1 {
citrixlist -servers $serverlist1
}
workflow get-citrixlist2 {
citrixlist -servers $serverlist2
}
workflow get-citrixkill {
parallel {
get-citrixlist1
get-citrixlist2
}
}

input object powershell change

I am trying to change the $InvalidInput= $True from a linux to a powershell command. I can run the command through powershell and it tells me that $InvalidInput= $True is true and then comes back false.
I am lost on how to change this. Any information is helpful.
$InvalidInput= $true
if ( $n -eq 0 ) {
write-host "This script sets up TF90 Staging"
write-host -n "Which production do you `enter code here`want to run?(RB/TaxLocator/Cyclic)"
read $ProductionDistroenter code here
} else {
$ProductionDistro=$1
}
while { $InvalidInput = $true }
do
if ($ProductionDistro = $RB -o $ProductionDistro = $TaxLocator -o $ProductionDistro = $Cyclic) {
$InvalidInput=$false
break continue
} else {
write-host "You have entered an error"
write-host "You must type RB or TaxLocator or Cyclic"
write-host "you typed $ProductionDistro"
write-host "This script sets up TF90 Staging"
read $ProductionDistro
}
original question asked. ^
The full script will be poseted below so you can see what I am trying to do.
function Copy-File {
#.Synopsis
# Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
param}($TFL09143.pkg,"d/tf90/code_stg","d/tf90bp/code_stg","d/tf90lm/code_stg","d/tf90pv/code_stg")
# create destination if it's not there ...
#mkdir $destination -force -erroraction SilentlyContinue
foreach($original in ls $source -recurse) {
$result = $original.FullName.Replace($source,$destination)
while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
if($original.PSIsContainer) {
# mkdir $result -ErrorAction SilentlyContinue
# } else {
copy $original.FullName -destination $result
}
}
{$InvalidInput=$true}
if ( $n -eq 0 ) {
write-host "This script sets up TF90 Staging"
write-host -n "Which production do you want to run? (RB/TaxLocator/Cyclic)"
$ProductionDistro
else
$ProductionDistro=$1
}
( $InvalidInput = $true)
if ( $ProductionDistro = $RB, $ProductionDistro = $TaxLocator, $ProductionDistro = $Cyclic
){
( $InvalidInput=$false )
break
} else {
write-host "You have entered an error"
write-host "You must type RB or TaxLocator or Cyclic"
write-host "you typed $ProductionDistro"
write-host "This script sets up TF90 Staging"
$ProductionDistro
}
{$InvalidInput=$true}
if ($n -eq 0) {
write-host "This script sets up RB TF90 Staging"
write-host -n "Which Element do you want to run? (TF90/TF90BP/TF90LM/TF90PV/ALL)"
read $ElementDistro
else
$ElementDistro=$1
}
( $InvalidInput = $true )
If ( $ElementDistro = $TF90, $ElementDistro = $TF90BP, $ElementDistro = $TF90LM, $ElementDistro = $TF90PV, $ElementDistro = $ALL
){
( $InvalidInput=$false )
break
} else {
write-host "You have entered an error"
write-host "You must type TF90 or TF90BP or TF90LM or TF90PV"
write-host "you typed $ElementDistro"
write-host "This script sets up TF90 Staging"
$ElementDistro
}
if ( $ElementDistro = $TF90 ) {
cd /d/tf90/code_stg
function Execute-MySQLCommand {param( [string]$app03bsi, #the host name of the SQL server
[string]$TF90NCS, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "TF90_CONNECT_STRING=DSN=TF90NCS;Description=TF90NCS;Trusted_Connection=Yes;WSID=APP03-
BSI;DATABASE=TF90NCS;DATASET=DEFAULT"
$Command.CommandType = SET # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
install -y ../TFL09143.pkg
}
if ( $ElementDistro = $TF90BP ) {
cd /d/tf90bp/code_stg
function Execute-MySQLCommand {param( [string]$app03bsi, #the host name of the SQL server
[string]$TF90BPS, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "TF90_CONNECT_STRING=DSN=TF90BPS; Description=TF90BPS; Trusted_Connection=Yes;WSID=APP03-
BSI;DATABASE=TF90BPS;"
$Command.CommandType = SET # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
install ../TFL09143.pkg
}
if ( $ElementDistro = $TF90LM ) {
cd /d/tf90lm/code_stg
function Execute-MySQLCommand {param( [string]$app03bsi, #the host name of the SQL server
[string]$TF90LMS, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "TF90_CONNECT_STRING=DSN=TF90LMS;Description=TF90LMS;Trusted_Connection=Yes;WSID=APP03-
BSI;DATABASE=TF90LMS;"
$Command.CommandType = SET # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
install ../TFL09143.pkg
}
if ( $ElementDistro = $TF90PV ) {
cd /d/tf90pv/code_stg
function Execute-MySQLCommand {param( [string]$app03bsi, #the host name of the SQL server
[string]$TF90PVS, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "TF90_CONNECT_STRING=DSN=TF90PVS;Description=TF90PVS;Trusted_Connection=Yes;WSID=APP03-
BSI;DATABASE=TF90PVS;"
$Command.CommandType = SET # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
install ../TFL09143.pkg
}}}}
the out that is produced is
d/tf90/code_stg
d/tf90bp/code_stg
d/tf90lm/code_stg
d/tf90pv/code_stg
This script sets up TF90 Staging
$InvalidInput=$true
True
You have entered an error
You must type TF90 or TF90BP or TF90LM or TF90PV
you typed
This script sets up TF90 Staging
after it shows this nothing happens and nothing has been done. My goal is to get it to ask what production i want to choose and let me choose it and also ask what element I want to choose and load the package into the folder. None of this has been done.
I think an easier way to do this would be to prompt the user for their input, and then do a While ([User Input] -NotMatch RB or TaxLocator or Cyclic) {Give error and ask again}. Mind you, that's pseudocode but I think that's going to serve you better than what you're working with. Check this code out:
write-host "This script sets up TF90 Staging"
$ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(RB/TaxLocator/Cyclic)"
While($ProductionDistro -notmatch "(RB|TaxLocator|Cyclic)"){
write-host "`nYou have entered an error" -ForegroundColor Red
write-host "You must type RB or TaxLocator or Cyclic"
write-host "you typed $ProductionDistro"
write-host "This script sets up TF90 Staging"
$ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(RB/TaxLocator/Cyclic)"
}

How do I find the Collection Membership Information with PowerShell

I have the following code, but I get an "Invalid Namespace" error constantly, I am pretty sure I am entering the correct information.
If you have another way of doing this, it's also accepted.
Param(
$SiteCode,
$SourceFile,
$Destination = "$env:USERPROFILE\DESKTOP\Computers.csv"
)
$Computers = Get-Content $SourceFile
$EmptyArray = #()
foreach($computer in $computers)
{
$ResourceIDQuery = Get-WmiObject -Namespace "root\sms\site_$SiteCode" -Class SMS_R_SYSTEM -Filter "Name='$computer'"
$CollectionQuery = Get-WmiObject -Namespace "root\sms\site_$SiteCode" -Class SMS_CollectionMember_a -filter "ResourceID='$($ResourceIDQuery.ResourceId)'"
foreach($Item in $CollectionQuery)
{
$DObject = New-Object PSObject
$Dobject | Add-Member -MemberType NoteProperty -Name "Computer" -Value $computer
$Dobject | Add-Member -MemberType NoteProperty -Name "ResID" -Value $($ResourceIDQuery.ResourceId)
$Dobject | Add-Member -MemberType NoteProperty -Name "CollID" -Value $($Item.CollectionId)
$Dobject | Add-Member -MemberType NoteProperty -Name "DirectOrNot" -Value $($Item.IsDirect)
$EmptyArray += $Dobject
}
}
$EmptyArray | ConvertTo-Csv -NoTypeInformation | Out-File $Destination
Rather than connecting to each computer and extracting the information (slow) get it from the straight from the database....
[CmdletBinding()]
param (
[string] $hosts = "",
[string] $sccmsrv = "",
[Parameter(Mandatory=$False,Position=3)]
[string] $path = ""
)
$usage = "USAGE: List-AdvertCollMembershipSCCM.ps1 -sccmsrv SCCMSERVER -hosts 'host1 host2 host3' -path 'c:\temp\Outfile.csv'"
if ($host -and $sccmsrv){
Write-Host ""
Write-Host -ForegroundColor Yellow "SCCM Server: $sccmsrv"
Write-Host -ForegroundColor Yellow "Looking at hosts: $hosts"
#### Function for executing a SQL query with integrated authentication
function execSQLQuery ([string]$fSQLServer, [string]$db, [string]$query){
$objConnection = New-Object System.Data.SqlClient.SqlConnection
$objConnection.ConnectionString = "Server = $fSQLServer; Database = $db; trusted_connection=true;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand $query, $objConnection
trap {Write-Host -ForegroundColor 'red' "($sqlsrv/$db not accessible)";continue}
$SqlCmd.Connection.Open()
if ($SqlCmd.Connection.State -ine 'Open') {
$SqlCmd.Connection.Close()
return
}
$dr = $SqlCmd.ExecuteReader()
#get the data
$dt = new-object "System.Data.DataTable"
$dt.Load($dr)
$SqlCmd.Connection.Close()
$dr.Close()
$dr.Dispose()
$objConnection.Close()
return $dt
}
# read the SCCM site name of the SCCM site server
$site = (gwmi -ComputerName $sccmsrv -Namespace root\sms -Class SMS_ProviderLocation).sitecode
# enumerating SQL server name for the given SCCM site server
$sccmCompquery = gwmi -q "Select distinct SiteSystem, Role, SiteCode FROM SMS_SiteSystemSummarizer where role = 'SMS SQL Server' and siteCode = '$site' ORDER BY SiteCode" -namespace "root\sms\site_$site" -ComputerName $sccmsrv
[string]$tmpstr = [regex]::Match($sccmCompquery.sitesystem, "\\\\\w+\\$")
$sccmSQLServer = $tmpstr.replace("\", "")
$objColl = #()
#### Collate the host list.
$hostlist = #($Input)
if ($hosts) {
if($hosts -imatch " "){
$hostsArr = #($hosts.split(" "))
$hostlist += $hostsArr
}
else{
$hostlist += $hosts
}
}
# going through the list of hosts
foreach($srv in $hostlist){
$memberQuery = "SELECT dbo.v_FullCollectionMembership.Name AS 'Hostname', dbo.v_GS_SYSTEM.ResourceID, dbo.v_Collection.Name AS 'Collection Name', dbo.v_Collection.CollectionID, dbo.v_FullCollectionMembership.IsDirect "
$memberQuery += "FROM dbo.v_FullCollectionMembership INNER JOIN dbo.v_Collection ON dbo.v_FullCollectionMembership.CollectionID = dbo.v_Collection.CollectionID INNER JOIN dbo.v_GS_SYSTEM ON dbo.v_FullCollectionMembership.ResourceID = dbo.v_GS_SYSTEM.ResourceID "
$memberQuery += "WHERE (LOWER(dbo.v_FullCollectionMembership.Name) = LOWER('$srv'))"
# running sql query to enumerate list of collections the computer is member of
$membership = execSQLQuery $sccmSQLServer "SMS_$site" $memberQuery
# if we have a result, go through it and build an object collection with the computer name and the collection(s) it is member of
if($membership){
foreach($enumColl in $membership){
$sObject = $enumColl | select Hostname, ResourceID, "Collection Name", CollectionID, IsDirect
$objColl +=$sObject
}
}
}
if ($objColl){
if ($path){
$objColl | ft -AutoSize
Write-Host -ForegroundColor Yellow "Exporting to results to: $path"
$objColl | Export-Csv $path -NoTypeInformation
}
else{
$objColl | ft -AutoSize
Write-Host -ForegroundColor Green "Use the -path argument in the command line to export output to csv to display"
Write-Host -ForegroundColor Green "the 'IsDirect' Information"
Write-Host ""
}
}
Else {
foreach ($Hostname in $hostlist){
Write-Host ""
Write-Host -ForegroundColor Yellow "The host $hostname is not a member of any collection"
}
Write-Host -ForegroundColor Yellow "Check you have entered the correct hostname and try again"
}
}
else {
Write-Host ""
Write-Host -ForegroundColor Yellow $usage
}
Execution:-
PS C:\> ListSCCMCollections.ps1 -sccmsrv SCCMSERVER -hosts host1,host2,host3 -path "c:\temp\Outfile.csv"
or
PS C:\> Get-Content hostlist.txt | ListSCCMCollections.ps1 -sccmsrv SCCMSERVER -path c:\temp\Outfile.csv
Getting the requested info straight from SQL:-
SELECT dbo.v_FullCollectionMembership.Name AS 'Hostname', dbo.v_GS_SYSTEM.ResourceID, dbo.v_Collection.Name AS 'Collection Name', dbo.v_Collection.CollectionID,
dbo.v_FullCollectionMembership.IsDirect
FROM dbo.v_FullCollectionMembership INNER JOIN
dbo.v_Collection ON dbo.v_FullCollectionMembership.CollectionID = dbo.v_Collection.CollectionID INNER JOIN
dbo.v_GS_SYSTEM ON dbo.v_FullCollectionMembership.ResourceID = dbo.v_GS_SYSTEM.ResourceID
WHERE (LOWER(dbo.v_FullCollectionMembership.Name) = LOWER('Hostname'))
This script can be used with any SQL query on the SCCM database. All you need to do is update the SQL query in the script. i.e. the $memberQuery array (if you spread the query over a couple of lines like below, be sure to leave a space at the end of each line with exception to the last).
For example; If you'd like the script to show the clients collections with live advertisements assigned to them change the SQL query in the $memberQuery array to:-
$memberQuery = "SELECT dbo.v_FullCollectionMembership.Name AS 'Hostname', dbo.v_GS_SYSTEM.ResourceID, dbo.v_Collection.Name AS 'Collection Name',dbo.v_Collection.CollectionID, dbo.v_FullCollectionMembership.IsDirect, dbo.v_Advertisement.AdvertisementID, dbo.v_Advertisement.AdvertisementName "
$memberQuery += "FROM dbo.v_FullCollectionMembership INNER JOIN dbo.v_Collection ON dbo.v_FullCollectionMembership.CollectionID = dbo.v_Collection.CollectionID INNER JOIN dbo.v_GS_SYSTEM ON dbo.v_FullCollectionMembership.ResourceID = dbo.v_GS_SYSTEM.ResourceID INNER JOIN dbo.v_Advertisement ON dbo.v_Collection.CollectionID = dbo.v_Advertisement.CollectionID "
$memberQuery += "WHERE (LOWER(dbo.v_FullCollectionMembership.Name) = LOWER('$srv'))"
and the $sObject variable to:-
$sObject = $enumColl | select Hostname, ResourceID, "Collection Name", CollectionID, IsDirect, AdvertisementID, AdvertisementName
Complete script to view client collections with live advisements (execution the same as before):-
[CmdletBinding()]
param (
[string] $hosts = "",
[string] $sccmsrv = "",
[Parameter(Mandatory=$False,Position=3)]
[string] $path = ""
)
$usage = "USAGE: List-AdvertCollMembershipSCCM.ps1 -sccmsrv SCCMSERVER -hosts 'host1 host2 host3' -path 'c:\temp\Outfile.csv'"
if ($host -and $sccmsrv){
Write-Host ""
Write-Host -ForegroundColor Yellow "SCCM Server: $sccmsrv"
Write-Host -ForegroundColor Yellow "Looking at hosts: $hosts"
#### Function for executing a SQL query with integrated authentication
function execSQLQuery ([string]$fSQLServer, [string]$db, [string]$query){
$objConnection = New-Object System.Data.SqlClient.SqlConnection
$objConnection.ConnectionString = "Server = $fSQLServer; Database = $db; trusted_connection=true;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand $query, $objConnection
trap {Write-Host -ForegroundColor 'red' "($sqlsrv/$db not accessible)";continue}
$SqlCmd.Connection.Open()
if ($SqlCmd.Connection.State -ine 'Open') {
$SqlCmd.Connection.Close()
return
}
$dr = $SqlCmd.ExecuteReader()
#get the data
$dt = new-object "System.Data.DataTable"
$dt.Load($dr)
$SqlCmd.Connection.Close()
$dr.Close()
$dr.Dispose()
$objConnection.Close()
return $dt
}
# read the SCCM site name of the SCCM site server
$site = (gwmi -ComputerName $sccmsrv -Namespace root\sms -Class SMS_ProviderLocation).sitecode
# enumerating SQL server name for the given SCCM site server
$sccmCompquery = gwmi -q "Select distinct SiteSystem, Role, SiteCode FROM SMS_SiteSystemSummarizer where role = 'SMS SQL Server' and siteCode = '$site' ORDER BY SiteCode" -namespace "root\sms\site_$site" -ComputerName $sccmsrv
[string]$tmpstr = [regex]::Match($sccmCompquery.sitesystem, "\\\\\w+\\$")
$sccmSQLServer = $tmpstr.replace("\", "")
$objColl = #()
#### Collate the host list.
$hostlist = #($Input)
if ($hosts) {
if($hosts -imatch " "){
$hostsArr = #($hosts.split(" "))
$hostlist += $hostsArr
}
else{
$hostlist += $hosts
}
}
# going through the list of hosts
foreach($srv in $hostlist){
$memberQuery = "SELECT dbo.v_FullCollectionMembership.Name AS 'Hostname', dbo.v_GS_SYSTEM.ResourceID, dbo.v_Collection.Name AS 'Collection Name',dbo.v_Collection.CollectionID, dbo.v_FullCollectionMembership.IsDirect, dbo.v_Advertisement.AdvertisementID, dbo.v_Advertisement.AdvertisementName "
$memberQuery += "FROM dbo.v_FullCollectionMembership INNER JOIN dbo.v_Collection ON dbo.v_FullCollectionMembership.CollectionID = dbo.v_Collection.CollectionID INNER JOIN dbo.v_GS_SYSTEM ON dbo.v_FullCollectionMembership.ResourceID = dbo.v_GS_SYSTEM.ResourceID INNER JOIN dbo.v_Advertisement ON dbo.v_Collection.CollectionID = dbo.v_Advertisement.CollectionID "
$memberQuery += "WHERE (LOWER(dbo.v_FullCollectionMembership.Name) = LOWER('$srv'))"
# running sql query to enumerate list of collections the computer is member of
$membership = execSQLQuery $sccmSQLServer "SMS_$site" $memberQuery
# if we have a result, go through it and build an object collection with the computer name and the collection(s) it is member of
if($membership){
foreach($enumColl in $membership){
$sObject = $enumColl | select Hostname, ResourceID, "Collection Name", CollectionID, IsDirect, AdvertisementID, AdvertisementName
$objColl +=$sObject
}
}
}
if ($objColl){
if ($path){
$objColl | ft -AutoSize
Write-Host -ForegroundColor Yellow "Exporting to results to: $path"
$objColl | Export-Csv $path -NoTypeInformation
}
else{
$objColl | ft -AutoSize
Write-Host -ForegroundColor Green "Use the -path argument in the command line to export output to csv to display"
Write-Host -ForegroundColor Green "the header 'AdvertisementName'"
Write-Host ""
}
}
Else {
foreach ($Hostname in $hostlist){
Write-Host ""
Write-Host -ForegroundColor Yellow "The host $hostname is not a member of any collection with live advertisements"
}
Write-Host -ForegroundColor Yellow "Check you have entered the correct hostname and try again"
}
}
else {
Write-Host ""
Write-Host -ForegroundColor Yellow $usage
}
And if you connect to SCCM from station with only SCCM Console installed and every other SCCM cmdlets works, trying Get-WmiObject:
Get-WmiObject -Namespace "root\sms\site_$SiteCode" ...
you will have an error:
“Get-WmiObject : Invalid namespace …”
In this situation you should specify parameter ComputerName and point to server where SCCM is installed:
Get-WmiObject -ComputerName "SCCMserver" -Namespace "root\sms\site_$SiteCode" ...
Hope it helps, I waste few minutes by this.