Loop PS from specific line - powershell

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.
}

Related

How to ping continuously in the background in powershell?

This is my first program in powershell, Im trying to get from the user input and then pinging the IP address or the hostname, Creating text file on the desktop.
But if the user wants the add more than one IP I get into infinite loop.
Here Im asking for IP address.
$dirPath = "C:\Users\$env:UserName\Desktop"
function getUserInput()
{
$ipsArray = #()
$response = 'y'
while($response -ne 'n')
{
$choice = Read-Host '
======================================================================
======================================================================
Please enter HOSTNAME or IP Address, enter n to stop adding'
$ipsArray += $choice
$response = Read-Host 'Do you want to add more? (y\n)'
}
ForEach($ip in $ipsArray)
{
createFile($ip)
startPing($ip)
}
}
Then I creating the file for each IP address:
function createFile($ip)
{
$textPath = "$($dirPath)\$($ip).txt"
if(!(Test-Path -Path $textPath))
{
New-Item -Path $dirPath -Name "$ip.txt" -ItemType "file"
}
}
And now you can see the problem, Because I want the write with TIME format, I have problem with the ForEach loop, When I start to ping, And I cant reach the next element in the array until I stop
the cmd.exe.
function startPing($ip)
{
ping.exe $ip -t | foreach {"{0} - {1}" -f (Get-Date), $_
} >> $dirPath\$ip.txt
}
Maybe I should create other files ForEach IP address and pass params?
Here's a old script I have. You can watch a list of computers in a window.
# pinger.ps1
# example: pinger yahoo.com
# pinger c001,c002,c003
# $list = cat list.txt; pinger $list
param ($hostnames)
#$pingcmd = 'test-netconnection -port 515'
$pingcmd = 'test-connection'
$sleeptime = 1
$sawup = #{}
$sawdown = #{}
foreach ($hostname in $hostnames) {
$sawup[$hostname] = $false
$sawdown[$hostname] = $false
}
#$sawup = 0
#$sawdown = 0
while ($true) {
# if (invoke-expression "$pingcmd $($hostname)") {
foreach ($hostname in $hostnames) {
if (& $pingcmd -count 1 $hostname -ea 0) {
if (! $sawup[$hostname]) {
echo "$([console]::beep(500,300))$hostname is up $(get-date)"
$sawup[$hostname] = $true
$sawdown[$hostname] = $false
}
} else {
if (! $sawdown[$hostname]) {
echo "$([console]::beep(500,300))$hostname is down $(get-date)"
$sawdown[$hostname] = $true
$sawup[$hostname] = $false
}
}
}
sleep $sleeptime
}
pinger microsoft.com,yahoo.com
microsoft.com is down 11/08/2020 17:54:54
yahoo.com is up 11/08/2020 17:54:55
Have a look at PowerShell Jobs. Note that there are better and faster alternatives (like thread jobs, runspaces, etc), but for a beginner, this would be the easiest way. Basically, it starts a new PowerShell process.
A very simple example:
function startPing($ip) {
Start-Job -ScriptBlock {
param ($Address, $Path)
ping.exe $Address -t | foreach {"{0} - {1}" -f (Get-Date), $_ } >> $Path
} -ArgumentList $ip, $dirPath\$ip.txt
}
This simplified example does not take care of stopping the jobs. So depending on what behavior you want, you should look that up.
Also, note there there is also PowerShell's equivalent to ping, Test-Connection

Speed Powershell Script Up

I am looking for way to speed up my Powershell script. I have a script that returns the manager Employee ID and manager name based on a .txt file that has the samaccountnames for each user under that manager. The problem is the list is very long, about 1400+ names and the script is taking forever to run. Here is my script. It works, just looking for a way to speed it up:
cls
If (!(Get-Module -Name activerolesmanagementshell -ErrorAction SilentlyContinue))
{
Import-Module activerolesmanagementshell
}
Write-host $("*" * 75)
Write-host "*"
Write-host "* Input file should contain just a list of samaccountnames - no header row."
Write-host "*"
Write-host $("*" * 75)
$File = Read-Host -Prompt "Please supply a file name"
If (!(test-path $File))
{
Write-host "Sorry couldn't find the file...buh bye`n`n"
exit
}
get-content $File | %{
$EmpInfo = get-qaduser -proxy -Identity $_ -IncludedProperties employeeid,edsva_SSCOOP_managerEmployeeID
# Check if we received back a Manager ID - if yes, get the Manager's name
# If not, set the Manager Name to "NONE" for output
If ($($EmpInfo.edsva_SSCOOP_managerEmployeeID).length -gt 2)
{
# Get the Manager's name from AD
$($EmpInfo.edsva_SSCOOP_managerEmployeeID)
$ManagerName = $(Get-QADUser -SearchAttributes #{employeeid=$($EmpInfo.edsva_SSCOOP_managerEmployeeID)} | select name).name
If (!$ManagerName)
{
$ManagerName = "NONE"
}
# Add the Manager name determined above (or NONE) to the properties we'll eventually output
$EmpInfo | Add-Member -MemberType NoteProperty -Name ManagerName -Value $ManagerName
}
Else
{
$EmpInfo.edsva_SSCOOP_managerEmployeeID = "NONE"
}
# Output user samaccountname edsva_SSCOOP_managerEmployeeID and ManagerName to a file
$EmpInfo | select samaccountname,edsva_SSCOOP_managerEmployeeID,ManagerName | export-csv "C:\Users\sfp01\Documents\Data_Deletion_Testing\Script_DisaUser_MgrEmpID\Disabled_Users_With_Manager.txt" -NoTypeInformation -Append
} # End of file processing loop
Ok, first things first... asking your user to type in a file name. Give them a nice friendly dialog box with little effort. Here's a function I keep on hand:
Function Get-FilePath{
[CmdletBinding()]
Param(
[String]$Filter = "All Files (*.*)|*.*|Comma Seperated Values (*.csv)|*.csv|Text Files (*.txt)|*.txt",
[String]$InitialDirectory = $home,
[String]$Title)
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $InitialDirectory
$OpenFileDialog.filter = $Filter
$OpenFileDialog.Title = $Title
[void]$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename
}
Then you can do:
$File = Get-FilePath -Filter 'Text Files (*.txt)|*.txt|All Files (*.*)|*.*' -InitialDirectory "$home\Desktop" -Title 'Select user list'
That doesn't speed things up, it's just a quality of life improvement.
Secondly, your 'can't find the file' message will appear as the window closes, so the person that ran your script probably won't see it. Towards that end I have a function that I use to pause a script with a message.
Function Invoke-Pause ($Text){
[reflection.assembly]::LoadWithPartialName('Windows.Forms')|out-null
If($psISE){
[Windows.Forms.MessageBox]::Show("$Text", "Script Paused", [Windows.Forms.MessageBoxButtons]"OK", [Windows.Forms.MessageBoxIcon]"Information") | ?{(!($_ -eq "OK"))}
}Else{
Write-Host $Text
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
With that you can get a message to the user, and then close the script so the user knows what happened. This function works in both the PowerShell console, as well as in the PowerShell ISE. In the console you get a text message that you define, and then a 'Press any key to continue...' message, and it waits for the user to press a key. In the ISE it pops up a window with your message, and waits for the user to click the OK button before proceeding. You could do something like:
If(!(Test-Path $File)){Invoke-Pause "Sorry couldn't find the file...buh bye";exit}
Now to get on to speeding things up!
You have more than one employee per manager right? So why look up the manager more than once? Setup a hashtable to keep track of your manager info, and then only look them up if you can't find them in the hashtable. Before your loop declare $Managers as a hashtable that just declares that 'NONE' = 'NONE', then inside the loop populate it as needed, and then reference it later.
Also, you are appending to a file for each user. That means PowerShell has to get a file lock on the file, write to it, close the file, and release the lock on it... over and over and over and over... Just pipe your users down the pipeline and write to the file once at the end.
Function Get-FilePath{
[CmdletBinding()]
Param(
[String]$Filter = "All Files (*.*)|*.*|Comma Seperated Values (*.csv)|*.csv|Text Files (*.txt)|*.txt",
[String]$InitialDirectory = $home,
[String]$Title)
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $InitialDirectory
$OpenFileDialog.filter = $Filter
$OpenFileDialog.Title = $Title
[void]$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename
}
cls
If (!(Get-Module -Name activerolesmanagementshell -ErrorAction SilentlyContinue))
{
Import-Module activerolesmanagementshell
}
Write-host $("*" * 75)
Write-host "*"
Write-host "* Input file should contain just a list of samaccountnames - no header row."
Write-host "*"
Write-host $("*" * 75)
$File = Get-FilePath -Filter 'Text Files (*.txt)|*.txt|All Files (*.*)|*.*' -InitialDirectory "$home\Desktop" -Title 'Select user list'
If (!(test-path $File))
{
Write-host "Sorry couldn't find the file...buh bye`n`n"
exit
}
$Managers = #{'NONE'='NONE'}
Get-Content $File | %{
$EmpInfo = get-qaduser -proxy -Identity $_ -IncludedProperties employeeid,edsva_SSCOOP_managerEmployeeID
Switch($EmpInfo.edsva_SSCOOP_managerEmployeeID){
{$_.Length -lt 2} {$EmpInfo.edsva_SSCOOP_managerEmployeeID = 'NONE'}
{$_ -notin $Managers.Keys} {
$MgrLookup = Get-QADUser -SearchAttributes #{employeeid=$EmpInfo.edsva_SSCOOP_managerEmployeeID} |% Name
If(!$MgrLookup){$MgrLookup = 'NONE'}
$Managers.add($EmpInfo.edsva_SSCOOP_managerEmployeeID,$MgrLookup)
}
}
Add-Member -InputObject $EmpInfo -NotePropertyName 'ManagerName' -NotePropertyValue $Managers[$EmpInfo.edsva_SSCOOP_managerEmployeeID] -PassThru
} | select samaccountname,edsva_SSCOOP_managerEmployeeID,ManagerName | Export-Csv "C:\Users\sfp01\Documents\Data_Deletion_Testing\Script_DisaUser_MgrEmpID\Disabled_Users_With_Manager.txt" -NoTypeInformation -Append

Delete local administrator account with delete() method ADSI with Powershell

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)

Wont move past first while statement

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.

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)"
}