MS Excel to Database - database

I am searching for a way to transfer an Excel file to a database (the client is called mbox. Is there a general way to transfer Excel to a database?). At least I want a script writing the INSERT-commands for me. I tried it with PowerShell but run into one huge problem: I can't write a proper for-each-loop for this task:
if($Args.count -eq 0){
"No Parameter-Error"
exit
}
if($Args.count -gt 1){
"Too many Parameter-Error"
exit
}
if (-not (Test-path $args[0] -include *.csv)){
"Invaild Root or no csv-file"
exit
}
$spalten=Import-Csv $args[0] -Delimiter ";"
$spalten.GetEnumerator() | % {
$key=$($_.key);
Echo "$key"
Echo $($_.value[$key])+"`n";
}
Please help, also know that I have no idea what one column will be named.

Related

uninstall using registry uninstall string powershell

I'm trying to create a powershell script that will uninstall all versions of a program in our studio.
I had a look at the registry and can see that we have 3 strings of the program installed in our studio computers
{D4BE10F2-3E2D-4120-863A-765623D53264}
{77067FD9-800C-48B4-803D-569642ADABC5}
{1DB1AEB7-EDBD-4BB1-87DB-26C72576DA42}
I created a test script:
msiexec.exe /x{D4BE10F2-3E2D-4120-863A-765623D53264} /q
and used it on a machine, this worked and that version of the program was uninstalled.
I want to create a script that cycle all 3 strings and Success on the correct one, as I don't know what machine has what version without doing a scan.
so I created a `powershell script:
foreach ($guid in '{D4BE10F2-3E2D-4120-863A-765623D53264}',
'{77067FD9-800C-48B4-803D-569642ADABC5}',
'{1DB1AEB7-EDBD-4BB1-87DB-26C72576DA42}') {
$exe = 'C:\Windows\System32\msiexec.exe'
$ps = Start-Process -PassThru -Wait $exe "/x /q"
if ($ps.ExitCode -eq 0) { "Success"; exit 0 }
}
Write-Warning "Uninstallation failed."
exit $ps.ExitCode
This is not working for me as it keeps returning with Uninstallation failed, I'm not sure whats going on.
Any advice?
This will work even if there are all three versions installed:
foreach ($guid in '{D4BE10F2-3E2D-4120-863A-765623D53264}',
'{77067FD9-800C-48B4-803D-569642ADABC5}',
'{1DB1AEB7-EDBD-4BB1-87DB-26C72576DA42}') {
$exe = 'C:\Windows\System32\msiexec.exe'
$ps = Start-Process $exe -ArgumentList "/x$guid /q" -PassThru -Wait
if ($ps.ExitCode -eq 0) {
Write-Host "$($guid): Success"
} else {
Write-Host "$($guid): Failed"
}
}

Powershell Looping issue with process before next loop

I am new to Powershell and I am having an issue within a loop that I need assistance with. I am attempting to rename some files that are created as part of the process within the loop.
I have tested the code OUTSIDE of the loop and it works fine. However, when I try to put it in the loop, nothing seems to happen.
The files I need to rename are in the following locations…
(1)“\MYSERVER\MYCOMPANY\MYFOLDER\ MyPrintouts\EstimateImport\ImportPrintout.txt”
(2)“\MYSERVER\MYCOMPANY\MYFOLDER\ MyPrintouts\PostEntries\ImportPostEntries.txt”
I need to tack the date and time on the end. This code works for me OUTSIDE of the loop. I put it in a file I named RenameFiles.ps1
#File location
$ImportPrintout = “\\MYSERVER\MYCOMPANY\MYFOLDER\MyPrintouts\EstimateImport\ImportPrintout.txt”
$ImportPostEntries = “\MYSERVER\MYCOMPANY\MYFOLDER\ MyPrintouts\PostEntries\ImportPostEntries.txt”
#Find and rename the import printouts
Get-ChildItem $ImportPrintout -Filter "ImportPrintout.txt" | ForEach-Object {
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')$(Get-Date -Format "MMddyyyy-HHmmss").txt"}
Get-ChildItem $ImportPostEntries -Filter "ImportPostEntires.txt" | ForEach-Object {
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')$(Get-Date -Format "MMddyyyy-HHmmss").txt"}
This is how I added it to the loop as I want the files renamed BEFORE the next file is processed…
#Define actions after an Event is Detected
$action = {$files = Get-ChildItem -Path $watcher.Path -Filter $watcher.Filter #-Recurse
foreach ($file in $files)
{
#Define variables for log file
$changeType = $Event.SourceEventArgs.ChangeType #Your event trigger "Created"
$fileDate = $file.LastWriteTime #Date/Time Estimate was created
#logline contains = Date/Time of import, Created, Date/Time Created, filename
$logline = "$(Get-Date), $changeType, $fileDate, $file"
#Actions to take ==============================================================
#Write details to the log
Add-Content "“\\MYSERVER\MYCOMPANY\MYFOLDER\EstimateImportLog.txt" -value $logline
#Copy the estimate to the "ToBeProcessed" folder
Copy-Item $file.FullName -Destination $copyTo
#Move the estimate to the "EstimateHistory" folder
Move-Item $file.FullName -Destination $moveTo -Force
#Run the powershell script that launches the .bat file that launches the macro
Invoke-Expression "& '\\MYSERVER\MYCOMPANY\MYFOLDER\PSscriptToRunBATfile.ps1'"
#Pause the script for 30 seconds to allow the estimate to finish posting
Start-Sleep -Seconds 30
Invoke-Expression "& '“\\MYSERVER\MYCOMPANY\MYFOLDER\RenameFiles.ps1'"
}
}
This seems to “break” my loop. However, I need this to be done BEFORE going to the next file. How can I accomplish renaming these files before moving on. Any assistance would be greatly appreciated. Thank you!
As far as the loop failing, you're probably encountering an error. Either set your $ErrorActionPreference to Continue or set it to Stop and wrap try/catch blocks around your copy-item and move-item to detect and handle errors.
That probably also addresses the failure of the copy-item/move-item to change the file name, it's running into an error trying to perform that action and failing.

How to check if a scheduled Powershell script has failed to run in Nagios

I have a requirement where I need to be notified when a scheduled Powershell script fails at any point of time. I would like to configure a Nagios service for this, and need someone to point me in the right direction.
Cheers.
Shadab
There may be a power shell-specific way of doing this, but let me give you two ideas:
1) is there some output of the program that you can monitor? A log file that gets touched when the script runs, etc? If so, you can monitor that file in nagios.
or,
2) can you modify the script to send an "I finished" message to nagios? If so, you can setup a notification when that message has not been received (goes "stale").
You need to use exit codes. Check out documentation on Nagios Plugin API, but below are the exit/return codes you should use in your script:
Plugin Return Code Service State Host State
0 OK UP
1 WARNING UP or DOWN/UNREACHABLE
2 CRITICAL DOWN/UNREACHABLE
3 UNKNOWN DOWN/UNREACHABLE
Here's an example of a script I wrote for an Icinga check, maybe this will help give you some ideas?: (http://www.baremetalwaveform.com/?p=311 for full article)
$state = (rstcli64 --information --volume 2> Out-Null | select-string -Pattern "State:") -split "`r"
If (
($state.count -gt 0) -and ($state.count -eq ($state | Where-Object -FilterScript {$_ -match "Normal"}).count)
)
{
#OK
Write-Host "RST Volume state OK"
exit 0
}
If (
$state.count -eq 0
)
{
#UNKNOWN
Write-Host "RST Volume state UNKNOWN"
exit 3
}
else
{
#CRITICAL
Write-Host "RST Volume state CRITICAL"
exit 2
}

How to add an element back into an array

First off, I am new to Powershell, so please excuse any poor coding here.
I'm trying to write a script that queues commands. We have a piece of equipment that can only handle 32 commands at one time. What I want to do is build a command file that has many more than 32 commands and then it automatically queues any command after 32 until another free slot opens up. Everything seems to be working except when I go into my 'else' statement. I attempt to add the current $_ back into the array so it doesn't get lost and gets reprocessed, but this does not seem to be working.
I build my array from a text file:
$commands = #(Get-Content C:\scripts\temp\commands.txt)
When I try to add the current $_ value back into the array during the 'else' pause statement, it never adds back in, so that one particular command never enters back into the array. So if my script has to pause 15 times, 15 commands will never get ran as they just get processed by the 'else' statement and get thrown out of my 'if/else' loop.
Here's my if/else loop:
$commands | ForEach-Object {
If (Test-Path C:\scripts\temp\active_migrations.txt){
Remove-Item C:\scripts\temp\active_migrations.txt
}
CMD.EXE /C "ssh $user#$cluster -pw $PlainPassword lsmigrate" > C:\scripts\temp\active_migrations.txt
$count = Get-Content C:\scripts\temp\active_migrations.txt
$number_of_migrations = $count.Length / 6
IF ($number_of_migrations -lt 32)
{
Write-Host "Migrations are currently at $number_of_migrations. Proceeding with next vdisk migration."
Write-Host "Issuing command $_"
Write-Host "There are still $migrations_left migrations to execute of $total_migrations total."
Write-Host ""
CMD.EXE /C "ssh $user#$cluster -pw $PlainPassword $_"
SLEEP 2
$migrations_left--
}
ELSE
{
Write-Host "Migrations are currently at $number_of_migrations. Sleeping for 1 minute"
$commands = #($commands + $_)
Write-Host "There are still $migrations_left migrations to execute of $total_migrations total."
SLEEP 60
}}
}
Any help is much appreciated.
Thank you Paul. I ended up dumping things during the else statement to a temp array and it works! Appreciate the assistance.
function commands_temp
{
if (Test-Path C:\scripts\temp\commands_temp.txt)
{
$commands=#()
$commands=#(Get-Content C:\scripts\temp\commands_temp.txt)
Remove-Item C:\scripts\temp\commands_temp.txt
Proceed
}
Else
{
Write-Host "All migrations are either complete or successfully executed. Check the GUI or run lsmigrate CLI command for full status."

list contents with batch

I need a bat file that will list the entire contents of a folder Including its subfolders in a text file.
one of our programs seams to constantly be missing or adding files. a list would help me trackdown the issue(s).
Wouldn't this do it?
dir C:\autocad /s /b > output.txt
If you have PowerShell, you can use this instead:
cd *<targetdirectory>*
ls -r |% { $_.FullName } | Set-Content foldercontents.txt
I only bring it up, because you can then compare the next time you check to see differences:
$original = Get-Content foldercontents.txt;
$now = ls -r |% { $_.FullName }
Write-Host "Missing Files:";
$original |? { -not $($now -contains $_) };
Write-Host "Added Files:";
$now |? { -not $($original -contains $_) };
If your problem is just tracking down what is the program that is creating and removing files, you may monitor all the file accesses in the system with Sysinternals Process Monitor http://technet.microsoft.com/en-us/sysinternals/bb896645 . An easy way to watch all the file accesses being done by any process.

Resources