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)"
}
Related
So I writing some code to run some patching on AWS, I have the following script snippet taken out of the whole thing for now.. I seem to be running into an issue with $PSBoundParameters..
(It's Friday & I've had a long week so I may just need to sleep on it) - but I can't seem to pass anything out of read-host...
param (
[Parameter(Mandatory = $true)][ValidateNotNullorEmpty()][string]$Prof,
[Parameter(Mandatory = $false)][ValidateNotNullorEmpty()][string]$Reminder,
[Parameter(Mandatory = $false)][ValidateNotNullorEmpty()][string]$AddToTGs,
[Parameter(Mandatory = $false)][ValidateNotNullorEmpty()][string]$PatchType,
[Parameter(Mandatory = $false)][ValidateNotNullorEmpty()][string]$Instance,
[Parameter(Mandatory = $false)][ValidateNotNullorEmpty()][string]$Environment
)
function PromptInstance {
$Instance = Read-Host -Prompt "Please Specify the Instance"
Write-Host "Using: $Instance" -ForegroundColor Cyan
}
function PromptEnvtoPatch {
$Environment = Read-Host -Prompt "Please Specify the Environment (e.g. dev)"
Write-Host "Using: $Environment" -ForegroundColor Cyan
}
function PromptReminder {
$title = "Calendar"
$message = "Do you want to Add an Outlook Reminder in 24 Hrs?"
$pA = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Adds an Outlook Reminder"
$pB = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Won''t add a reminder"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($pA, $pB)
$CalResult = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($CalResult)
{
0 {
$global:CalRes = 1
Write-Host "Reminder will be added.." -ForegroundColor Cyan
}
1 {
$global:CalRes = 0
Write-Host "No Reminder will be added.." -ForegroundColor Cyan
}
}
}
function PromptAddToTGs {
$title = "Re-Add to Target Groups"
$message = "Do you want to have this script Automatically add the instances back into the Target Groups after Patching?"
$pA = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Will ADD the instance back into Target Groups"
$pB = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Will NOT add the instance back into Target Groups"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($pA, $pB)
$result = $host.ui.PromptForChoice($title, $message, $options, 1)
switch ($result)
{
0 {
$global:AddTGRes = 1
Write-Host "Instances WILL be added back into Target Groups" -ForegroundColor Cyan
}
1 {
$global:AddTGRes = 0
Write-Host "Instances will NOT be added back into Target Groups" -ForegroundColor Cyan
}
}
}
function PromptPatchType {
$title = "Patching Type"
$message = "Do you want to Patch a Single Instance, or ALL Instances for a specific Team Env?"
$pA = New-Object System.Management.Automation.Host.ChoiceDescription "&Instance", "Patches an Instance"
$pB = New-Object System.Management.Automation.Host.ChoiceDescription "&ALL Instances for an Env", "Patches ALL Instances in a Team Env"
$pQ = New-Object System.Management.Automation.Host.ChoiceDescription "&Quit", "Cancel/Exit"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($pA, $pB, $pQ)
$PatchResult = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($PatchResult)
{
0 {
$Instance = Read-Host "Please Specify the Instance Id"
}
1 {
$Environment = Read-Host "Please Specify the Team (i.e. dev)"
}
2 {
Write-Host "You Quitter!... :-)"
Exit
}
}
}
function KickOffPatchingEnv {
param ($Prof, $Reg, $Reminder, $AddToTGs, $PatchType, $Environment)
Write-Host "Using the Following Options: (Profile:$Prof) (Region:$Reg) (Reminder:$Reminder) (AddToTGs:$AddToTGs) (PatchType:$PatchType) (Environment:$Environment)"
}
function KickOffPatchingInst {
param ($Prof, $Reg, $Reminder, $AddToTGs, $PatchType, $Instance)
Write-Host "Using the Following Options: (Profile:$Prof) (Region:$Reg) (Reminder:$Reminder) (AddToTGs:$AddToTGs) (PatchType:$PatchType) (Instance:$Instance)"
}
switch -wildcard ($Prof) {
"*dev*" { $Reg = "eu-west-1"; $Bucket = "s3-dev-bucket" }
"*admin*" { $Reg = "eu-west-1"; $Bucket = "s3-admin-bucket" }
"*prod*" { $Reg = "eu-west-1"; $Bucket = "s3-prod-bucket" }
"*staging*" { $Reg = "eu-west-1"; $Bucket = "s3-staging-bucket" }
}
if (!$PSBoundParameters['Reminder']) { PromptReminder }
if (!$PSBoundParameters['AddToTGs']) { PromptAddToTGs }
if ($PSBoundParameters['PatchType']) {
if (($PatchType -eq "i") -or ($PatchType -eq "instance") -or ($PatchType -eq "I") -or ($PatchType -eq "Instance")) {
if (!$PSBoundParameters['Instance']) { PromptInstance }
KickOffPatchingInst $Prof $Reg $Reminder $AddToTGs $PatchType $Instance
}
if (($PatchType -eq "a") -or ($PatchType -eq "all") -or ($PatchType -eq "A") -or ($PatchType -eq "All")) {
if (!$PSBoundParameters['Environment']) { PromptEnvtoPatch }
KickOffPatchingEnv $Prof $Reg $Reminder $AddToTGs $PatchType $Environment
}
} else { PromptPatchType }
If I use the parameters on the command line, it works fine..
PS C:\Users\myself\Desktop> .\test.ps1 -Prof dev -Reminder y -AddToTGs y -PatchType a -Environment dev
Using the Following Options: (Profile:dev) (Region:eu-west-1) (Reminder:y) (AddToTGs:y) (PatchType:a) (Environment:dev)
But if I omit an option, say for instance the Environment, I'm prompted for it, but the value is not displayed..
PS C:\Users\myself\Desktop> .\test.ps1 -Prof dev -Reminder y -AddToTGs y -PatchType a
Please Specify the Environment (e.g. dev): dev
Using: dev
Using the Following Options: (Profile:dev) (Region:eu-west-1) (Reminder:y) (AddToTGs:y) (PatchType:a) (Environment:)
Environment is empty....
I've tried loads of different things such as setting global:Environment etc, but I always seem to be missing out whichever variable isn't specified in the command?
Maybe this isn't the best way to write this, but i've never used $PSBoundParameters before so this is my first time trying it out..
Can anyone see my glaring error here at all?
TIA :)
#Mathias R. Jessen answered this for me.
I put this in the function
function PromptProfile {
$Prof = Read-Host -Prompt "Please Specify the Profile"
$global:UserProf = $Prof
}
then changed code later on with the global variable, so I can use them
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.
}
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!"
I am writing a powershell script to manage our local administrator accounts using a csv file.
#variable to store the data in data.csv
$userobjects = Import-CSV C:-data.csv
function main-list{
Write-Host "--------------------------------------"
Write-Host "Windows Powershell Account Manager"
Write-Host "--------------------------------------"
Write-Host "1 - Change Name"
Write-Host "2 - Disabled Account"
Write-Host "3 - Delete User"
Write-Host "4 - Exit"
[int]$action = Read-Host "Enter the menu number from above"
if ($action -eq 1){change-name}
if ($action -eq 2){disable-account}
if ($action -eq 3){delete-user}
if ($action -eq 4){cls; break}
}
function change-name
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
# Rename
if (($user.Account -ne $user.Rename) -and ($user.Rename -ne '' ))
{
#Write-Host "old name :"$FileHostname"/"$FileAccount "-> new name :"$FileHostname"/"$FileNewname
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://$connection")
if ($accName.path -eq "WinNT://"+$connection+"")
{
$accName.psbase.Rename($FileNewname)
Write-Host "Account(s) renamed"
$user.Account = $user.Rename
}
else
{
Write-Host "Account name :"$connection "can't be found on the host"
}
$user.Account = $user.Rename
$userobjects | export-csv C:-data.csv -notype
}
}
Write-Host "--------------------------------------"
main-list
}
function disable-account
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
if ($user.Disable -eq 'yes')
{
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://"+$connection+"")
if ($accName.UserFlags -eq '515')
{
Write-Host "Account :"$connection "is already disabled"
}
else
{
$accName.description = "Account disabled"
$accName.UserFlags = 2
$accName.setinfo()
Write-Host "Account(s) disabled"$connection
}
}
}
Write-Host "--------------------------------------"
main-list
}
function delete-user
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
#Delete
if ($user.Delete -eq 'yes')
{
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://"+$connection+"")
$accName.delete("user",$accName.name)
#Write-Host $connection deleted
}
else
{
Write-Host "Account name :"$connection "can't be found on the host"
}
}
}
}
$userobjects | export-csv C:-\data.csv -notype
main-list
I don't really know why I have this message when I am trying to use the delete function : "Unknown name", it is like it doesn't find the local account to delete it but I am not sure. However, It works perfectly when I want to rename or disable accounts.
My data file looks like that
http://www.noelshack.com/2016-05-1454622367-capture.png
I will post the real message when I will be back to work tomorow.
Thank you for your help.
Quick skim... wouldn't this need to be used instead? I think your $accName.name would be using the machine name.
$accName.delete("user",$user.account)
You delete() the user from the computer, so your [adsi] object should bind to the computer and call Delete() on that instead:
# Just the machine name, nothing more:
$Machine = [ADSI]"WinNT://$FileHostname"
# Now delete the user account from the machine
$Machine.Delete('user',$FileAccount)
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.