Monitor a folder using Powershell and check it against a SQL table and send an email out if file doesn't exists in the last 6 hours - sql-server

I am using powershell to check a folder and when a file gets added to the folder, it queries a sql table and if there hasn't been a file added in the last 6 hours then it will send an email to several people letting them know that the file was copied/uploaded to that folder.
I can send the email when a file gets added, but when I added the code to check the SQL table, it stopped working. Can someone help me figure out the rest of this script?
[code]
# make sure you adjust this to point to the folder you want to monitor
$PathToMonitor = "U:\temp\test"
explorer $PathToMonitor
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $true
# make sure the watcher emits events
$FileSystemWatcher.EnableRaisingEvents = $true
# define the code that should execute when a file change is detected
$Action = {
$details = $event.SourceEventArgs
$Name = $details.Name
$FullPath = $details.FullPath
$OldFullPath = $details.OldFullPath
$OldName = $details.OldName
$ChangeType = $details.ChangeType
$Timestamp = $event.TimeGenerated
$JustPath = Path.GetDirectoryName($FullPath)
# SQL Work ---------------------------------------------------------------------
$Server = 'SQL01'
$Database = 'FTP_Upload'
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$text = "{0} was {1} at {2}" -f $FullPath, $ChangeType, $Timestamp
$sql = "IF Not Exists (Select 1 From Transmit Where DateDiff(IsNull(TimeGenerated, '01/01/2020 01:00:00 PM'), '$Timestamp') < 6 ) AND PathOnly = '$JustPath' )
BEGIN
Insert Transmit(FullPath, PathOnly, TimeGenerated)
Values('$FullPath', '$JustPath', '$Timestamp')
END "
Write-Host ""
Write-Host $text -ForegroundColor Green
Write-Host $sql
# you can also execute code based on change type here
switch ($ChangeType)
{
'Created' {
# Check SQL to see if there has been a file ftp'd in the last 6 hours ------
$Command.CommandText = $sql
$Command.ExecuteReader()
$Connection.Close()
# Send Email ---------------------------------
$EmailFrom = “email1#domain1.com”
$EmailTo = “email2#domain2.com, email3#domain3.com”
$Subject = “FTP Notification”
$Body = $text
$SMTPServer = “smtp.office365.com”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“email1#domain1.com”, “password”);
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Start-Sleep -Seconds 5
$SMTPClient.Dispose()
# this executes only when a file was renamed
$text = "File {0} was Created" -f $FullPath
Write-Host $text -ForegroundColor Yellow
}
default { Write-Host $_ -ForegroundColor Red -BackgroundColor White }
}
}
# add event handlers
$handlers = . {
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Changed -Action $Action -SourceIdentifier FSChange
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreate
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Deleted -Action $Action -SourceIdentifier FSDelete
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Renamed -Action $Action -SourceIdentifier FSRename
}
Write-Host "Watching for changes to $PathToMonitor"
try
{
do
{
Wait-Event -Timeout 1
Write-Host "." -NoNewline
} while ($true)
}
finally
{
# this gets executed when user presses CTRL+C
# remove the event handlers
Unregister-Event -SourceIdentifier FSChange
Unregister-Event -SourceIdentifier FSCreate
Unregister-Event -SourceIdentifier FSDelete
Unregister-Event -SourceIdentifier FSRename
# remove background jobs
$handlers | Remove-Job
# remove filesystemwatcher
$FileSystemWatcher.EnableRaisingEvents = $false
$FileSystemWatcher.Dispose()
"Event Handler disabled."
}
[/code]

Related

Powershell script equivalent of database -> Generate scripts

I wrote a PowerShell script which stores schema, and data info in .sql file.
But in that file I am missing the initiate part of create database. The file starts with queries of create table.
PowerShell script:
$Filepath= 'C:\Temp' # local directory to save build-scripts to
$DataSource= 'ServerName' #'SERVERNAME' # server name and instance
$Database= 'DBName'
$DateTime = Get-Date -Format s
$dateStamp = $(get-date).ToString("yyyyMMdd");
$ErrorActionPreference = "stop"
$ms='Microsoft.SqlServer'
$v = [System.Reflection.Assembly]::LoadWithPartialName( "$ms.SMO")
if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9') {
[System.Reflection.Assembly]::LoadWithPartialName("$ms.SMOExtended") | out-null
}
$My="$ms.Management.Smo" #
$s = new-object ("$My.Server") $DataSource
if ($s.Version -eq $null ){Throw "Can't find the instance $Datasource"}
$db= $s.Databases[$Database]
if ($db.name -ne $Database){Throw "Can't find the database '$Database' in $Datasource"};
$transfer = new-object ("$My.Transfer") $db
$transfer.Options.ScriptBatchTerminator = $true
$transfer.Options.ToFileOnly = $true
$transfer.Options.ScriptData = $true
$transfer.Options.IncludeHeaders = $true
$transfer.Options.ExtendedProperties = $true
$transfer.Options.IncludeDatabaseContext = $true
$transfer.Options.DriForeignKeys = $true
$transfer.Options.DriIndexes = $true
$transfer.Options.DriPrimaryKey = $true
$transfer.Options.DriUniqueKeys = $true
$transfer.CreateTargetDatabase = $true
$transfer.Options.Filename = "$($FilePath)\$($Database)_$($dateStamp)_Build.sql";
$transfer.EnumScriptTransfer()
Any help on how this can be achieved?
Basically I am missing create database block in my .sql file.

How do you script out SQL Server agent jobs to single or individual files

I've tried various Powershell scripts but they fail with:
The following exception occurred while trying to enumerate the collection: "An exception occurred while executing a Transact-SQL statement or batch.".
At H:\Create_SQLAgentJobSripts2.ps1:89 char:22
foreach ($job in $s.JobServer.Jobs)
~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
FullyQualifiedErrorId : ExceptionInGetEnumerator
What has gone wrong or how can I get better debugging on this error?
I executed this script:
.\Create_SQLAgentJobSripts2.ps1 .\ServerNameList.txt
Here's the script
param([String]$ServerListPath)
#write-host "Parameter: $ServerListPath"
#Load the input file into an Object array
$ServerNameList = get-content -path $ServerListPath
#Load the SQL Server SMO Assemly
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
#Create a new SqlConnection object
$objSQLConnection = New-Object System.Data.SqlClient.SqlConnection
#For each server in the array do the following.
foreach($ServerName in $ServerNameList)
{
Write-Host "Beginning with Server: $ServerName"
Try
{
$objSQLConnection.ConnectionString = "Server=$ServerName;Initial Catalog=CED_NCT_RESOURCE_TRACK;Persist Security Info=True;User ID=CEDNCTAdmin;Password=CEDNCTAdmin;"
Write-Host "Trying to connect to SQL Server instance on $ServerName..." -NoNewline
$objSQLConnection.Open() | Out-Null
Write-Host "Success."
$objSQLConnection.Close()
}
Catch
{
Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
$errText = $Error[0].ToString()
if ($errText.Contains("network-related"))
{Write-Host "Connection Error. Check server name, port, firewall."}
Write-Host $errText
continue
}
# Won't be using this object again
Remove-Variable -Name objSQLConnection
#If the output folder does not exist then create it
$OutputFolder = ".\$ServerName"
if (!(Test-Path $OutputFolder))
{
write-host ("Creating directory: " + $OutputFolder)
New-Item -ItemType directory -Path $OutputFolder
}
else
{
write-host ("Directory already exists: " + $OutputFolder)
}
write-host "File: $(".\$OutputFolder\" + $($_.Name -replace '\\', '') + ".job.sql")"
# Connect to the instance using SMO
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $ServerName
write-host ("SQL Server Edition: " + $s.Edition)
write-host ("SQL Agent ErrorLogFile: " + $s.JobServer.ErrorLogFile)
# Instantiate the Scripter object and set the base properties
$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($ServerName)
write-host ("SCRP ToString():" + $scrp.ToString())
write-host ("Test scrp - Server: " + $scrp.Server)
#The next step is to set the properties for the script files:
$scrp.Options.ScriptDrops = $False
$scrp.Options.WithDependencies = $False
$scrp.Options.IncludeHeaders = $True
$scrp.Options.AppendToFile = $False
$scrp.Options.ToFileOnly = $True
$scrp.Options.ClusteredIndexes = $True
$scrp.Options.DriAll = $True
$scrp.Options.Indexes = $False
$scrp.Options.Triggers = $False
$scrp.Options.IncludeIfNotExists = $True
#Now, we can cycle through the jobs and create scripts for each job on the server.
# Create the script file for each job
foreach ($job in $s.JobServer.Jobs)
{
$jobname = $job.Name
write-host ("Job: " + $jobname)
$jobfilename = ($OutputFolder + "\" + $jobname + ".job.sql")
$scrp.Options.FileName = $jobfilename
write-host "Filename: $jobfilename"
#This line blows up
$scrp.Script($job)
}
}
Possibly you're not instantiating the Server object correctly. Try the following instead...
# Alternative 1: With servername and port, using Trusted Connection...
$ServerName = 'YourServerName,1433'
$ServerConnection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection -ArgumentList #( $ServerName )
# Alternative 2: With an SqlConnection object
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$ServerName;Initial Catalog=CED_NCT_RESOURCE_TRACK;Persist Security Info=True;User ID=CEDNCTAdmin;Password=CEDNCTAdmin;"
$SqlConnection.Open() | Out-Null
$ServerConnection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection -ArgumentList #( $SqlConnection )
# Then...
$Server = New-Object Microsoft.SqlServer.Management.Smo.Server -ArgumentList #( $ServerConnection )
$Server.JobServer.Jobs | ForEach-Object {
Write-Host "Job: $($_.Name)"
}

Run Multiple Script Instances

I work in an operations center with 10 screens on each computer. The main computer shows a lot of telemetry data and dashboards, graphs, animations, and a lot of other useful information via Chrome in a browser window. This is tedious to set up every time you reboot the computer, so I was very happy to find this original project: Chrome-Kiosk from https://alextomin.wordpress.com/2015/04/10/kiosk-mode-in-windows-chrome-on-multiple-displays/
It works very well as an auto starter in our operations center, so I am happy with that aspect of its functionality. But then I got to thinking: wouldn't it be useful if I could somehow temporarily display a webpage on the board, and have it close after a set time period so that the whole office can monitor an important event.
What I came up with is quite cool so far, and the people at work think that it is very useful, BUT, it needs more features. These are simple but I am stuck, I have been trying to figure this out for a while now. Below is the code that I am using.
Things that I can't get to work:
Kill Timer: I can get this to work by adding start-wait in front of the kill function that I have created, but that makes the looper.ps1 script sit and wait while the launcher.ps1 completes. How can I get the script to run without making the looper script stop until the other script finishes?
How can I track each new instance of Chrome that gets opened? Using the system ID does not seem to work, the best I can do is get-process and sort by chrome and the newest instance, which means that I can kill chrome instances that are younger than the timer value, but I am struggling to get this to work.
Any advice here would be appreciated.
SERVER SCRIPTS
I have put these into a folder called c:\scripts\ICVT
looper.ps1 - This will run constantly
Set-Location -Path C:\scripts\ICVT
while ($true) {
.\file_checker.ps1;
}
file_checker.ps1 - This is the script that looper runs. file_checker scans the folder for web.txt and mon.txt . Both must be present for the rest of the script to execute.
#Checks folder for web.txt and mon.txt . Both must be present for the rest of the script to execute
Set-Location -Path C:\scripts\ICVT
$a = Test-Path web.txt
$b = Test-Path mon.txt
if (($a -and $b -eq $True)) {
.\launcher.ps1
} else {
Write-Host "Scanning For Files"
}
Start-Sleep -Seconds 5
launcher.ps1 - This is just a modified version of the original script
$chromePath = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
$chromeArguments = '--new-window'
$web = (Get-Content -Path web.txt)
$mon = (Get-Content -Path mon.txt)
$timer = (Get-Content -Path $timer.txt)
# if Window not moved (especially on machine start) - try increasing the
# delay.
$ChromeStartDelay = 5
Set-Location $PSScriptRoot
. .\HelperFunctions.ps1
Chrome-Kiosk $web -MonitorNum $mon
#Delete parameters after use
Start-Sleep -Seconds 5
del web.txt
del mon.txt
del timer.txt
Here is the GUI that creates the web.txt, timer.txt and mon.txt files over the network
Set-Location -Path \\networkpc\folder
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
# Hide PowerShell Console
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 0)
function button ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) {
$Form = New-Object "system.Windows.Forms.Form";
$Form.ClientSize = '653,436'
$Form.text = "Display Board URL Tool"
$Form.TopMost = $false
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;
$iconBytes = [Convert]::FromBase64String($iconBase64)
$stream = New-Object IO.MemoryStream($iconBytes, 0, $iconBytes.Length)
$stream.Write($iconBytes, 0, $iconBytes.Length);
$iconImage = [System.Drawing.Image]::FromStream($stream, $true)
$Form.Icon = [System.Drawing.Icon]::FromHandle((New-Object System.Drawing.Bitmap -Argument $stream).GetHIcon())
$Button1 = New-Object "system.Windows.Forms.Button";
$Button1.text = "Screen 1"
$Button1.width = 132
$Button1.height = 77
$Button1.location = New-Object "System.Drawing.Point"(8,14);
$Button1.Font = 'Microsoft Sans Serif,10'
$Button2 = New-Object "system.Windows.Forms.Button";
$Button2.text = "Screen 2"
$Button2.width = 132
$Button2.height = 77
$Button2.location = New-Object "System.Drawing.Point"(165,14);
$Button2.Font = 'Microsoft Sans Serif,10'
$Button3 = New-Object "system.Windows.Forms.Button";
$Button3.text = "Screen 3"
$Button3.width = 132
$Button3.height = 77
$Button3.location = New-Object "System.Drawing.Point"(326,14);
$Button3.Font = 'Microsoft Sans Serif,10'
$Button4 = New-Object "system.Windows.Forms.Button";
$Button4.text = "Screen 4"
$Button4.width = 132
$Button4.height = 77
$Button4.location = New-Object "System.Drawing.Point"(483,15);
$Button4.Font = 'Microsoft Sans Serif,10'
$WinForm1 = New-Object "system.Windows.Forms.Form";
$WinForm1.ClientSize = '653,400'
$WinForm1.text = "Form"
$WinForm1.TopMost = $false
$Button5 = New-Object "system.Windows.Forms.Button";
$Button5.text = "Screen 5"
$Button5.width = 132
$Button5.height = 77
$Button5.location = New-Object "System.Drawing.Point"(8,117);
$Button5.Font = 'Microsoft Sans Serif,10'
$Button6 = New-Object "system.Windows.Forms.Button";
$Button6.text = "Screen 6"
$Button6.width = 132
$Button6.height = 77
$Button6.location = New-Object "System.Drawing.Point"(165,119);
$Button6.Font = 'Microsoft Sans Serif,10'
$Button7 = New-Object "system.Windows.Forms.Button";
$Button7.text = "Screen 7"
$Button7.width = 132
$Button7.height = 77
$Button7.location = New-Object "System.Drawing.Point"(326,119);
$Button7.Font = 'Microsoft Sans Serif,10'
$Button8 = New-Object "system.Windows.Forms.Button";
$Button8.text = "Screen 8"
$Button8.width = 132
$Button8.height = 77
$Button8.location = New-Object "System.Drawing.Point"(483,119);
$Button8.Font = 'Microsoft Sans Serif,10'
$Button9 = New-Object "system.Windows.Forms.Button";
$Button9.text = "Screen 9"
$Button9.width = 132
$Button9.height = 77
$Button9.location = New-Object "System.Drawing.Point"(9,220);
$Button9.Font = 'Microsoft Sans Serif,10'
$Button10 = New-Object "system.Windows.Forms.Button";
$Button10.text = "Screen 10"
$Button10.width = 132
$Button10.height = 77
$Button10.location = New-Object "System.Drawing.Point"(165,220);
$Button10.Font = 'Microsoft Sans Serif,10'
$Button11 = New-Object "system.Windows.Forms.Button";
$Button11.text = "Screen 11"
$Button11.width = 132
$Button11.height = 77
$Button11.location = New-Object "System.Drawing.Point"(326,220);
$Button11.Font = 'Microsoft Sans Serif,10'
$TextBox1 = New-Object "system.Windows.Forms.TextBox";
$TextBox1.multiline = $false
$TextBox1.width = 400
$TextBox1.height = 20
$TextBox1.location = New-Object "System.Drawing.Point"(220,314);
$TextBox1.Font = 'Microsoft Sans Serif,10'
$TextBox2 = New-Object "system.Windows.Forms.TextBox";
$TextBox2.multiline = $false
$TextBox2.width = 50
$TextBox2.height = 20
$TextBox2.location = New-Object "System.Drawing.Point"(220,348);
$TextBox2.Font = 'Microsoft Sans Serif,10'
$Label1 = New-Object "system.Windows.Forms.Label";
$Label1.text = "Display Time (Minutes)"
$Label1.AutoSize = $true
$Label1.width = 25
$Label1.height = 10
$Label1.location = New-Object "System.Drawing.Point"(15,348);
$Label1.Font = 'Microsoft Sans Serif,10'
$Label2 = New-Object "system.Windows.Forms.Label";
$Label2.text = "URL for Timed Monitoring"
$Label2.AutoSize = $true
$Label2.width = 25
$Label2.height = 10
$Label2.location = New-Object "System.Drawing.Point"(15,314);
$Label2.Font = 'Microsoft Sans Serif,10'
$Button12 = New-Object "system.Windows.Forms.Button";
$Button12.text = "Kill Current Screen"
$Button12.width = 132
$Button12.height = 77
$Button12.location = New-Object "System.Drawing.Point"(483,220);
$Button12.Font = 'Microsoft Sans Serif,10'
$Button12.ForeColor = "#d0021b"
$Form.controls.AddRange(#($Button1,$Button2,$Button3,$Button4,$Button5,$Button6,$Button7,$Button8,$Button9,$Button10,$Button11,$TextBox1,$TextBox2,$Label1,$Label2,$Button12))
############# This is when you have to close the form after getting values
$eventHandler1 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '1'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler2 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '2'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler3 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '3'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler4 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '4'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler5 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '5'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler6 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '6'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler7 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '7'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler8 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '8'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler9 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '9'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler10 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '10'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler11 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Create mon.txt per button
$text = '11'
$text | Set-Content 'mon.txt'
$form.Close();};
$eventHandler12 = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
############# Kill the last Screen that was launched
$text = '1'
$text | Set-Content 'mon.txt'
$form.Close();};
$button1.Add_Click($eventHandler1) ;
$button2.Add_Click($eventHandler2) ;
$button3.Add_Click($eventHandler3) ;
$button4.Add_Click($eventHandler4) ;
$button5.Add_Click($eventHandler5) ;
$button6.Add_Click($eventHandler6) ;
$button7.Add_Click($eventHandler7) ;
$button8.Add_Click($eventHandler8) ;
$button9.Add_Click($eventHandler9) ;
$button10.Add_Click($eventHandler10) ;
$button11.Add_Click($eventHandler11) ;
$button12.Add_Click($eventHandler12) ;
#############Add controls to all the above objects defined
$form.Controls.Add($button1);
$form.Controls.Add($button2);
$form.Controls.Add($button3);
$form.Controls.Add($button4);
$form.Controls.Add($button5);
$form.Controls.Add($button6);
$form.Controls.Add($button7);
$form.Controls.Add($button8);
$form.Controls.Add($button9);
$form.Controls.Add($button10);
$form.Controls.Add($button11);
$form.Controls.Add($textLabel1);
$form.Controls.Add($textLabel2);
$form.Controls.Add($textBox1);
$form.Controls.Add($textBox2);
$ret = $form.ShowDialog();
#################return values
return $textBox1.Text, $textBox2.Text
}
#Creates the 3 txt files for web, mon and timer
$return = button "Monitoring Screen Selector" "Enter URL" "Enter Screen # from 1 to 11"
if ($return[0] -ne "") {
$return[0] > web.txt
}
if ($return[0] -eq "") {
exit
}
if ($return[1] -ne "") {
$return[1] > timer.txt
}
if ($return[1] -eq "") {
exit
}
#multiply by 60 to get minutes
if (Test-Path timer.txt) {
if ((Get-Item timer.txt).Length -gt 0kb) {
$result = Get-Content timer.txt
60 * $result > timer.txt
}
}
In order to do a lot of that functionality, you first need to get a Process Id for the Chrome window. In order to do that we need to make a few changes to the Chrome-Kiosk function to return that information. First I change the Start-Process to include the -PassThru parameter. That way I get a process object that I can get the PID from. Another edit to Get-Process to use the Id instead of "chrome", and finally we Write-Output the $Process object.
function Chrome-Kiosk($Url, $MonitorNum)
{
Write-Output "starting chrome $Url , monitor: $MonitorNum"
$Process = Start-Process $chromePath "$chromeArguments $Url" -PassThru
Start-Sleep -Seconds $ChromeStartDelay
$window = (Get-Process -Id $Process.Id | where MainWindowHandle -ne ([IntPtr]::Zero) | select -First 1).MainWindowHandle
$WinAPI::ShowWindow($window, [Tomin.Tools.KioskMode.Enums.ShowWindowCommands]::Restore)
$Helpers::MoveToMonitor($window, $MonitorNum)
$Helpers::SendKey($window, '{F11}')
Start-Sleep -Seconds $ChromeStartDelay
Write-Output $Process
}
The rest of the work is to modify the launcher script to have a kill timer. Essentially we pull the .txt deletion portion back into your file_checker.PS1 script so that we can launch the launcher.ps1 as a new self contained PowerShell process.
file_checker.PS1
#Checks folder for web.txt and mon.txt . Both must be present for the rest of the script to execute
Set-Location -Path C:\scripts\ICVT
$a = Test-Path web.txt
$b = Test-Path mon.txt
IF (($a -and $b -eq $True)) {
. .\launcher.ps1
#Delete parameters after use
del web.txt
del mon.txt
del timer.txt
}
else {
Write-Host "Scanning For Files"
}
Start-Sleep -Seconds 5
By using the modified Chrome-Kiosk function, where it returns the Process object of the Chrome window, we can now have the launcher script launch, sleep, and then kill only the Chrome window that we launched:
launcher.ps1
$chromePath = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
$chromeArguments = '--new-window'
$web = (Get-Content -Path web.txt)
$mon = (Get-Content -Path mon.txt)
$timer = (Get-Content -Path $timer.txt)
# if Window not moved (especially on machine start) - try increasing the
# delay.
$ChromeStartDelay = 5
Set-Location $PSScriptRoot
. .\HelperFunctions.ps1
$Process = Chrome-Kiosk $web -MonitorNum $mon
#Wait some period of time
Start-Sleep -Seconds 60
#Kill the process
Stop-Process $Process

Powershell - DataSet contains the number of records

I'm seeing some odd behavior. On my machine, PowerShell returns the recordset and I can iterate through the records no problem. On my co-worker's machine (who has access to the file share that I need to copy the files from) is getting a record count returned instead the actual records. I must be missing something easy. Any idea why I'm seeing this different behavior?
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = server; Database = db; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT fileName from SomeTable"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$Table = new-object data.datatable
$Table = $DataSet.tables[0]
$SqlConnection.Close()
function Out-FileForce {
PARAM($path)
PROCESS
{
if(Test-Path $path)
{
Out-File -inputObject $_ -append -filepath $path
}
else
{
new-item -force -path $path -value $_ -type file
}
}
}
foreach ($Row in $Table.Rows)
{
$fullPath = $Row.FullFilePathWithName
$path = "\\server\folder\"
$newPath = "C:\newFolder\"
$newDestination = $fullPath -replace [regex]::Escape($path), $newPath
#Write-Output $newDestination
#Write-Output $fullPath
# recurse should force the creation of the folder structure
#Copy-Item $fullPath $newDestination -recurse
Out-FileForce $newDestination
Copy-Item $fullPath $newDestination -force
Write-Output $newDestination " done"
}
This line:-
$SqlAdapter.Fill($DataSet)
returns the row count if you would like that for later assign it to something:-
$rowCount = $SqlAdapter.Fill($DataSet)
or if you don't require it:-
[void]$SqlAdapter.Fill($DataSet)
both of the above will avoid the need to skip 1
Hope this helps
Figured it out a fix, I'm still not sure why.
$DataSetTableRows was causing the issue
Fixing the original script I posted.
Added this to the top:
$Table = new-object data.datatable
$Table = $DataSet.tables[0]
Then in my loop I used $Table.Rows

Sql Server Script data: SMO.Scripter not working when output to file

I get this error message when I run the Powershell script at the bottom:
Exception calling "EnumScript" with "1" argument(s): "Script failed for Table 'dbo.Product'. "
At :line:48 char:35
+ foreach ($s in $scripter.EnumScript <<<< ($tbl)) { write-host $s }
However, when I comment out the output_file line
#$output_file="C:\Product.sql"
(which won't set the Scripter options to write to file), it works fine and outputs the INSERT statments to the console.
Here's the failing script, is there something I'm missing?
# Script INSERTs for given table
param
(
[string] $server,
[string] $database,
[string] $schema,
[string] $table,
[string] $output_file
)
$server="devdidb02"
$database="EPCTrunk_EPC"
$schema="dbo"
$table="Product"
$output_file="C:\Product.sql"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server
$db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
$tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($server)
# Get the database and table objects
$db = $srv.Databases[$database]
$tbl = $db.tables | Where-object {$_.schema -eq $schema-and$_.name -eq $table}
# Set scripter options to ensure only data is scripted
$scripter.Options.ScriptSchema = $false;
$scripter.Options.ScriptData = $true;
#Exclude GOs after every line
$scripter.Options.NoCommandTerminator = $true;
if ($output_file -gt "")
{
$scripter.Options.FileName = $output_file
$scripter.Options.ToFileOnly = $true
}
# Output the script
foreach ($s in $scripter.EnumScript($tbl)) { write-host $s }
I ran both yours and Keith's and it looks like the issue is in the path you are setting for the file. I was able to reproduce your error. You were using $output_file="C:\Product.sql". Then I changed the path to: $output_file="$home\Product.sql" it ran just fine and gave me the file.
I am guessing that the reason for this is that I don't have permission to write to c:\ which may be the problem you are having.
BTW - my home dir in this case for me is my user folder for my login so I was able to find it there.
FWIW I'm not able to repro the error you see using the AdventureWorks DB. The following generates the foo.sql file without any errors:
Add-Type -AssemblyName ('Microsoft.SqlServer.Smo, Version=10.0.0.0, ' + `
'Culture=neutral, PublicKeyToken=89845dcd8080cc91')
$serverName = '.\SQLEXPRESS'
$smo = new-object Microsoft.SqlServer.Management.Smo.Server $serverName
$db = $smo.Databases['AdventureWorks']
$tbl = $db.Tables | Where {$_.Schema -eq 'Production' -and `
$_.Name -eq 'Product'}
$output_file = "$home\foo.sql"
$scripter = new-object Microsoft.SqlServer.Management.Smo.Scripter $serverName
$scripter.Options.ScriptSchema = $false;
$scripter.Options.ScriptData = $true;
$scripter.Options.NoCommandTerminator = $true;
if ($output_file -gt "")
{
$scripter.Options.FileName = $output_file
$scripter.Options.ToFileOnly = $true
}
# Output the script
foreach ($s in $scripter.EnumScript($tbl)) { write-host $s }

Resources