Is there a way to export all the ODBC System DSNs from a windows 2003 machine?
System DSN information is stored under the HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI registry key. You could export that key to a .reg file and import on another machine.
UPDATE:
You can also do it programmatically. Here are a few examples:
http://www.codeproject.com/KB/database/DSNAdmin.aspx
http://support.microsoft.com/kb/110507
http://blogs.technet.com/b/heyscriptingguy/archive/2004/11/10/can-i-create-and-delete-a-dsn-using-a-script.aspx
I have just done this myself with a very simple bat script for 32bit ODBC sources
regedit /e c:\backup\odbc.reg "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ODBC\ODBC.INI"
and for the 64bit sources or if you are on a 32bit operating system:
regedit /e c:\backup\odbc.reg "HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI"
This backs up all of the DSN's however you could then specify the DNS you want.
System DSN's are stored in windows registry under HKLM\Software\ODBC\ODBC.INI node
So if you export this node to a *.reg file and run this reg file on a target machine, it should work.
The only thing, this reg file will contain some file paths which maybe computer specific, eg
c:\WINNT\System32\bla-bla-bla.dll includes WINNT folder which on target machine may be called like WINDOWS. So you will need to spend a bit time to make sure all paths in *.reg file are correct for target machine where you would finally import.
I wrote some Powershell functions for copying ODBC connections from one computer to another, they are posted (and kept updated) at:
http://powershell.com/cs/media/p/32510.aspx
# Usage:
# $srcConfig = Get-OdbcConfig srcComputerName
# Import-OdbcConfig trgComputerName $scrConfig
# Only returns data when setting values
function Get-OdbcConfig {
param( $srcName )
if ( Test-Connection $srcName -Count 1 -Quiet ) {
# cycle through the odbc and odbc32 keys
$keys = "SOFTWARE\ODBC\ODBC.INI", "SOFTWARE\Wow6432Node\ODBC\ODBC.INI"
foreach ( $key in $keys ){
# open remote registry
$type = [Microsoft.Win32.RegistryHive]::LocalMachine
$srcReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey( $type, $srcName )
$OdbcKey = $srcReg.OpenSubKey( $key )
# red through each key
foreach ( $oDrvr in $OdbcKey.GetSubKeyNames() ){
# form the key path
$sKey = $key + "\" + $oDrvr
$oDrvrKey = $srcReg.OpenSubKey( $sKey )
# cycle through each value, capture the key path, name, value and type
foreach ( $oDrvrVal in $oDrvrKey.GetValueNames() ) {
$regObj = New-Object psobject -Property #{
Path = $sKey
Name = $oDrvrVal
Value = $oDrvrKey.GetValue( $oDrvrVal )
Type = $oDrvrKey.GetValueKind( $oDrvrVal )
}
# dump each to the console
$regObj
}
}
}
}
# can't ping
else { Write-Host "$srcName offline" }
}
function Import-OdbcConfig {
param( $trgName, $srcConfig )
if ( Test-Connection $trgName -Count 1 -Quiet ) {
# open remote registry
$type = [Microsoft.Win32.RegistryHive]::LocalMachine
$trgReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey( $type, $trgName )
# sort out the key paths and cycle through each
$paths = $srcConfig | select -Unique Path
foreach ( $key in $paths ){
# check for the key and create it if it's not there
if ( ! $trgReg.OpenSubKey( $key.Path ) ) { $writeKey = $trgReg.CreateSubKey( $key.Path ) }
# open the path for writing ($true)
$trgKey = $trgReg.OpenSubKey( $key.Path, $true )
# cycle through each value, check to see if it exists, create it if it doesn't
foreach ( $oDrvr in $srcConfig | where { $_.Path -eq $key.Path } ) {
if ( ! $trgKey.GetValue( $oDrvr.Name ) ) {
$oType = $oDrvr.Type
$writeValue = $trgKey.SetValue( $oDrvr.Name, $oDrvr.Value, [Microsoft.Win32.RegistryValueKind]::$oType )
$objObj = new-object psobject -Property #{
Path = $oDrvr.Path
Name = $oDrvr.Name
Value = $trgKey.GetValue( $oDrvr.Name )
Type = $trgKey.GetValueKind( $oDrvr.Name )
}
}
$objObj
}
}
}
# can't ping
else { Write-Host "$srcName offline" }
}
Using these functions together you can copy all of one computers ODBC connections to another:
$srcConfig = Get-OdbcConfig srcComputerName
Import-OdbcConfig trgComputerName $scrConfig
It's possible to include only your favorite ODBC connection by filtering on the path:
Import-OdbcConfig trgComputerName ( $scrKeys | where { $_.Path -eq "SOFTWARE\ODBC\ODBC.INI\GoodDatabase" } )
Or filtering out ODBC connections you don't like:
Import-OdbcConfig trgComputerName ( $scrKeys | where { $_.Path -ne "SOFTWARE\ODBC\ODBC.INI\DatabaseIHate" } )
Import-OdbcConfig only returns data when setting values or can't ping target, if there's nothing to create it won't say anything.
If you can't find the registrations there, depending on if they are User DSN/System DSN, they can very will be in:
[HKEY_USERS\"User SID(dont' look for this, it will be a long
number)\Software\ODBC\ODBC.INI]
Related
I'm trying to test out asynchronous functionality in PowerShell 3.
So I figured I would query the uptimes of some servers remotely, and wrote the following script:
function getServerUptimes() {
# Obtain credentials for logging into
# the remote machines...
$cred = Get-Credential
$compsHash = #{
"server1.domain.com" = $null;
"server2.domain.com" = $null;
}
# Define an async block to run...no blocking in this script...
$cmd = {
param($computer, $dasCred)
Write-Host "which: $($computer)"
$session = new-cimsession $computer -Credential $dasCred
return (get-CimInstance win32_operatingsystem -CimSession $session | Select PScomputername, LastBootuptime);
}
ForEach($comp in $compsHash.Keys) {
Write-Host "${comp}"
# Kick off an async process to create a cimSession
# on each of these machines...
Start-Job -ScriptBlock $cmd -ArgumentList $comp, $cred -Name "Get$($comp)"
}
$results = Get-Job | Wait-Job | Receive-Job
# Retrieve the job, so we can look at the output
ForEach($comp in $compHash.Keys) {
$dasJob = Get-Job -Name "Get$($comp)"
Write-Host $dasJob.output
}
}
However, I don't really seem to get back any output in the resulting $dasJob object, I returned the value in my scriptblock, where is it going?
You already have the output (not including Write-Host output, of course) in the variable $results. In PowerShell you retrieve job output via Receive-Job. The property Output seems to always be empty (not sure why).
I have been working on a powershell script that uses a .txt file to download multiple files from tinyurls. I have been successful in using Jobs to make this happen simultaneously, thanks to those on this forum.
The project requires some pretty large files to be downloaded, and using the current method has no progress indicator. I figured some users might think the program died. Looking for a way give a status of where it is in the download. Here is what I came up with, but I'm lost in how to pipe this information back out to the console. Any suggestions?
#Checks to see if NT-Download folder is on the Desktop, if not found, creates it
$DOCDIR = [Environment]::GetFolderPath("Desktop")
$TARGETDIR = "$DOCDIR\NT-Download"
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
$filepaths = Resolve-Path "files.txt"
Get-Content "$filepaths" | Foreach {
Start-Job {
function Save-TinyUrlFile
{
PARAM (
$TinyUrl,
$DestinationFolder
)
$response = Invoke-WebRequest -Uri $TinyUrl
$filename = [System.IO.Path]::GetFileName($response.BaseResponse.ResponseUri.OriginalString)
$filepath = [System.IO.Path]::Combine($DestinationFolder, $filename)
$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
$responseStream = $response.GetResponseStream()
$buffer = new-object byte[] 10KB
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $count
try
{
$filestream = [System.IO.File]::Create($filepath)
$response.RawContentStream.WriteTo($filestream)
$filestream.Close()
while ($count -gt 0)
{
[System.Console]::CursorLeft = 0
[System.Console]::Write("Downloaded {0}K of {1}K", [System.Math]::Floor($downloadedBytes/1024), $totalLength)
$targetStream.Write($buffer, 0, $count)
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $downloadedBytes + $count
}
"`nFinished Download"
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Dispose()
}
finally
{
if ($filestream)
{
$filestream.Dispose();
}
}
}
Save-TinyUrlFile -TinyUrl $args[0] -DestinationFolder $args[1]
} -ArgumentList $_, "$TARGETDIR"
}
Have a look at Write-Progress
PS C:> for ($i = 1; $i -le 100; $i++ )
{write-progress -activity "Search in Progress" -status "$i% Complete:" -percentcomplete $i;}
Far more simple way : rely on Bits:
Start-BitsTransfer -Source $tinyUrl
In an effort to setup a "cron job" like scheduled task on Windows I've setup a Powershell script using code recommended via previous stackoverflow question.
I have some backups that I need to cleanup daily and delete old backups so I created a asp.net script to perform this task - the file name is BackupCleanup.aspx and I have confirmed that the ASP.net script does work when executed on its own by visiting the above url - I however cannot get it to execute using the Powershell script below.
The Powershell Script code I'm using is:
$request = [System.Net.WebRequest]::Create("http://127.0.0.1/BackupCleanup.aspx")
$response = $request.GetResponse()
$response.Close()
I have created this file with a PS1 extension, it shows properly in my os (Windows 2008) - I have tried both manually executing this task by right clicking and choosing "Run with Powershell" and also have scheduled this as a task - both to no avail.
I cannot figure out why the script does not work - any help would be GREATLY appreciated.
Here is the Powershell script I use to call up web pages using IE. Hopefully this will work for you as well.
Function NavigateTo([string] $url, [int] $delayTime = 100)
{
Write-Verbose "Navigating to $url"
$global:ie.Navigate($url)
WaitForPage $delayTime
}
Function WaitForPage([int] $delayTime = 100)
{
$loaded = $false
while ($loaded -eq $false) {
[System.Threading.Thread]::Sleep($delayTime)
#If the browser is not busy, the page is loaded
if (-not $global:ie.Busy)
{
$loaded = $true
}
}
$global:doc = $global:ie.Document
}
Function SetElementValueByName($name, $value, [int] $position = 0) {
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByName($name))
if ($elements.Count -ne 0) {
$elements[$position].Value = $value
}
else {
Write-Warning "Couldn't find any element with name ""$name"""
}
}
Function ClickElementById($id)
{
$element = $global:doc.getElementById($id)
if ($element -ne $null) {
$element.Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with id ""$id"""
break
}
}
Function ClickElementByName($name, [int] $position = 0)
{
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByName($name))
if ($elements.Count -ne 0) {
$elements[$position].Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with name ""$name"" at position ""$position"""
break
}
}
Function ClickElementByTagName($name, [int] $position = 0)
{
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByTagName($name))
if ($elements.Count -ne 0) {
$elements[$position].Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with tag name ""$name"" at position ""$position"""
break
}
}
#Entry point
# Setup references to IE
$global:ie = New-Object -com "InternetExplorer.Application"
$global:ie.Navigate("about:blank")
$global:ie.visible = $true
# Call the page
NavigateTo "http://127.0.0.1/BackupCleanup.aspx"
# Release resources
$global:ie.Quit()
$global:ie = $null
I had the same issue. I manually opened powershell and executed my script and I received "WebPage.ps1 cannot be loaded because running scripts is disabled on this system.".
You have to allow scripts to run
Execute the below in PowerShell
Set-ExecutionPolicy RemoteSigned -Scope LocalMachine
In my Corona SDK app I'm coping a sqlite database file to another location and then opening it.
It works fine in Corona Simulator on Mac OS as well as in Android build. But it doesn't work in Corona Simulator on Windows 8. The error message I have after a first database operation is "database disk image is malformed".
I found a problem description on Corona site
http://developer.coronalabs.com/forum/2011/07/09/sqlite-db-being-corrupted-windows
Does anybody know a solution for this issue?
Thought I would post the answer, even though this was posted a while back for future searchers:
Windows is picky when copying the file for the simulator. It requires that you specify that the database is going to be read and written as a binary file:
local fileSource = io.open( pathSource, "rb" )
local fileDest = io.open( pathDest, "wb" )
While it works fine in the Mac Corona Simulator without specifying the binary read/write, it is required for Windows development.
I know this is old, but the actual problem with the code on the link (besides the already mentioned by Dr. Brian Burton) is that they are not closing the initial opened file in case is not null. So instead of:
if( file == nil )then
-- Doesn't Already Exist, So Copy it In From Resource Directory
pathSource = system.pathForFile( dbName, system.ResourceDirectory )
fileSource = io.open( pathSource, "r" )
contentsSource = fileSource:read( "*a" )
-- Write Destination File in Documents Directory
pathDest = system.pathForFile( dbName, system.DocumentsDirectory )
fileDest = io.open( pathDest, "w" )
fileDest:write( contentsSource )
-- Done
io.close( fileSource )
io.close( fileDest )
end
you should add and ELSE clause at the end, like this:
if( file == nil )then
-- Doesn't Already Exist, So Copy it In From Resource Directory
pathSource = system.pathForFile( dbName, system.ResourceDirectory )
fileSource = io.open( pathSource, "rb" )
contentsSource = fileSource:read( "*a" )
-- Write Destination File in Documents Directory
pathDest = system.pathForFile( dbName, system.DocumentsDirectory )
fileDest = io.open( pathDest, "wb" )
fileDest:write( contentsSource )
-- Doneb
io.close( fileSource )
io.close( fileDest )
else
io.close(file)
end
Cheers!
How can I do a recursive walk through a local folder in order to upload everything it has inside it to the desired ftp folder? Here's what I have so far :
package require ftp
set host **
set user **
set pass **
set ftpdirectory **
set localdirectory **
proc upload {host user pass dir fileList} {
set handle [::ftp::Open $host $user $pass]
ftpGoToDir $handle $dir
# some counters for our feedback string
set j 1
set k [llength $fileList]
foreach i $fileList {
upload:status "uploading ($j/$k) $i"
::ftp::Put $handle $i
incr j
}
::ftp::Close $handle
}
#---------------
# feedback
#---------------
proc upload:status {msg} {
puts $msg
}
#---------------
# go to directory in server
#---------------
proc ftpGoToDir {handle path} {
::ftp::Cd $handle /
foreach dir [file split $path] {
if {![::ftp::Cd $handle $dir]} {
::ftp::MkDir $handle $dir
::ftp::Cd $handle $dir
}
}
}
proc watchDirChange {dir intv {script {}} {lastMTime {}}} {
set nowMTime [file mtime $dir]
if [string eq $lastMTime ""] {
set lastMTime $nowMTime
} elseif {$nowMTime != $lastMTime} {
# synchronous execution, so no other after event may fire in between
catch {uplevel #0 $script}
set lastMTime $nowMTime
}
after $intv [list watchDirChange $dir $intv $script $lastMTime]
}
watchDirChange $localdirectory 5000 {
puts stdout {Directory $localdirectory changed!}
upload $host $user $pass $ftpdirectory [glob -directory $localdirectory -nocomplain *]
}
vwait forever
Thanks in advance :)
You're already using the ftp package, so that means you've got tcllib installed. Good. That means in turn that you've got the fileutil package as well, and can do this:
package require fileutil
# How to do the testing; I'm assuming you only want to upload real files
proc isFile f {
return [file isfile $f]
}
set filesToUpload [fileutil::find $dirToSearchFrom isFile]
The fileutil::find command is very much like a recursive glob, except that you specify the filter as a command instead of via options.
You might prefer to use rsync instead though; it's not a Tcl command, but it is very good and it will minimize the amount of data actually transferred.