Remotely running SQL from PowerShell

Hi
I work for a Software House where checking files versions, running SQL to check tables is becoming run-of-the mill :)
I'm very new to PowerShell so far and have just been playing about to find that I can remotely check file-versions ok. Now onto the other side of the coin....running SQL to check tables is the next thing I need to learn.
Just for a heads-up. Most of the servers I connect to are running MS SQL Server 2003 (unfortanately) which is why I want to remotely check the servers without connecting in via Remote Desktop Session. With MS Server 2003, if I use a Remote Desktop
Session, I've found that I would have to download PowerShell (v1) and then have to configure it to allow it to run my .ps1 scripts which would also become cumbersome.
Can anyone give me a start and say how to remotely connect to and SQL database and then run a simple SELECT statement from PowerShell please. I can then build my powershell scripts up from there.
Kind Regards
Matt

Hi
I've tried this script but get the error below if anyone can help.
# Get SQL rows if they exist
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=\\10.1.2.3;Database=THEHOUSE;Integrated Security=True;User Id=Joe123;Password=password123"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT * FROM TABLEX WHERE TRANS_TYPE='ACG'"
$SqlCmd.Connection = $SqlConnection
$dbname = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
Write-output "Database is " $dbname
The error I get is:
Exception calling "Open" with "0" argument(s): "A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the
instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 25 - Connection string is not valid)"
At C:\PS1scripts\Get SQL table data.ps1:5 char:1
+ $SqlConnection.Open()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException
Exception calling "ExecuteScalar" with "0" argument(s): "ExecuteScalar requires an open and available
Connection. The connection's current state is closed."
At C:\PS1scripts\Get SQL table data.ps1:9 char:1
+ $dbname = $SqlCmd.ExecuteScalar()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException

Similar Messages

  • Run SQL from UNIX

    How could I run sqlplus from an Unix machine?

    If want to Install
    1. Need to Install Oracle Client
    2. Use SQL *PLUS
    or
    If dont want to install
    1. Use iSQLPLUS

  • How to run SQL from PL/SQL?

    hi,
    i want to run sql script from PL/SQL,
    in my PL/SQL,i have given the path within the double quotes,
    @"/usr/local/pbiace/current/bin/handle.sql" but while running the script im getting some exception.
    pls guide me.....

    What is your OS.
    First example, divide three part scritps and then
    cat beforepart.sql account.sql afterpart.sql | sqlplus user/password@connectstring
    type beforepart.sql+account.sql+afterpart.sql | sqlplus user/password@connectstring
    Second example, divide two part scripts.
    acc2.sql
    declare HandleN varchar(20);
    begin
    select pbhandlenamelower INTO HandleN from pb_handle where pbhandleid in(select max(pbhandleid)
    from pb_handle where ha_customerentityid in (select acct_customerentityid from account
    where acct_accountid = &1 )) AND pbmainhandleflag=1 ;
    do.pl('==============================') ;
    do.pl('Handle Name: ' || HandleN ) ;
    do.pl('==============================') ;
    EXCEPTION
    WHEN OTHERS THEN
    do.pl('No rows selected');
    END;
    exit
    main.sql
    set serveroutput on
    varaiable variable1 NUMBER
    DECLARE
    data varchar2(20);
    BEGIN
    data:='&1';
    select BI_ACCOUNTID into :variable1 from pb_bill_info where PBBTN=data;
    do.pl('BI_ACCOUNTID');
    do.pl('------------');
    do.pl(:variable1);
    end;
    @acc2 :variabl1
    Third Example
    create or replace directory SCRIPTS_DIR as 'path name'
    acc3.sql (Only 1 statement, don't include into-clause and ';')
    select pbhandlenamelower from pb_handle where pbhandleid in(select max(pbhandleid)
    from pb_handle where ha_customerentityid in (select acct_customerentityid from account
    where acct_accountid = :variable1 )) AND pbmainhandleflag=1
    main.sql
    set serveroutput on
    DECLARE
    data varchar2(20);
    variable1 NUMBER;
    HandleN varchar(20);
    p_sql varchar2(32000) := '';
    File_Handle UTL_FILE.FILE_TYPE;
    Read_line varchar2(4000);
    BEGIN
    data:='&1';
    select BI_ACCOUNTID into variable1 from pb_bill_info where PBBTN=data;
    do.pl('BI_ACCOUNTID');
    do.pl('------------');
    do.pl(variable1);
    File_Handle := UTL_FILE.FOPEN('SCRIPTS_DIR','acc3.sql','r');
    loop
    UTL_FILE.GET_LINE(File_Handle, Read_line);
    exit when no_data_found;
    p_sql := p_sql || Read_line || chr(32) ;
    end loop;
    UTL_FILE.FCLOSE(File_Handle);
    execute imediate p_sql into HandleN using varaiable1;
    do.pl('==============================') ;
    do.pl('Handle Name: ' || HandleN ) ;
    do.pl('==============================') ;
    EXCEPTION
    WHEN OTHERS THEN
    do.pl('No rows selected');
    END;
    Or Some many other Examples and those are maybe more simple, only if you would analyze your business requirements.

  • Getting Error when running sql from concurrent program in R12

    Hi All,
    I created concurrent program and attached EXECUTABLE which executable method as SQL plus .
    Using this program I am running one SQL file in R12 when I am running I am getting below error .
    Same king of program I have define in 11i and running it is running can anyone please help me if I need to do any set ups or security thing to resave this problem.
    ERROR:
    ORA-01017: invalid username/password; logon denied
    SP2-0306: Invalid option.
    Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
    where <logon> ::= <username>[<password>][@<connect_identifier>] | /
    SP2-0306: Invalid option.
    Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
    where <logon> ::= <username>[<password>][@<connect_identifier>] | /
    SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus
    Concurrent Manager encountered an error while running SQL*Plus for your concurrent request 3162719.
    Review your concurrent request log and/or report output file for more detailed information.
    Executing request completion options...
    Finished executing request completion options.
    Regrds,
    Sridhar.

    user12000862 wrote:
    Hi all,
    Thanks a lot giving replay below simple code I have put in my SQL file for testing Eventhough it is giving error .
    Table which i am using in Apps schema only.
    declare
    BEGIN
    insert into BRCD_HZ_DNB_XTBL_TEST values (666,'Y','547','Y','12254','TESTING','N','Y');
    commit;
    END;
    /Try this instead
    WHENEVER SQLERROR EXIT FAILURE ROLLBACK;
    WHENEVER OSERROR EXIT FAILURE ROLLBACK;
    insert into BRCD_HZ_DNB_XTBL_TEST values (666,'Y','547','Y','12254','TESTING','N','Y');
    commit;
    exit;HTH
    Srini

  • How to run SQL from OMB+

    For any of you who wanted to be able to query the database from OMB+ in order to gather object metadata or whatever as part of your deployment scripts, you have no doubt noticed (to your frustration) that this functionality is not provided.
    Sure, you can trigger execution of a sql/plus script as an external process, but that's hardly interactive now is it?
    the good news is that OMB+ DOES provide access to the standard java package, which of course means that you can utilize the standard java.sql classes, which means - JDBC.
    Here is a very simple starting point for you that provides simple connect, disconnect, and run query abilities. There is no exception handling and you'd need to add other functionality to execute prepared statements like procedure calls, or do DML like insert/update statement.
    Still, I hope that you find it of use as a starting point - if you need it. For documentation on the java.sql interfaces, go to the Sun Java Docs page at: http://java.sun.com/j2se/1.3/docs/api/ and scroll down to the java.sql package in the top left pane.
    Cheers,
    Mike
    package require java
    proc oracleConnect { serverName databaseName portNumber username password } {
       # import required classes
       java::import java.sql.Connection
       java::import java.sql.DriverManager
       java::import java.sql.ResultSet
       java::import java.sql.SQLWarning
       java::import java.sql.Statement
       java::import java.sql.ResultSetMetaData
       java::import java.sql.DatabaseMetaData
       java::import oracle.jdbc.OracleDatabaseMetaData
       # load database driver .
       java::call Class forName oracle.jdbc.OracleDriver
       # set the connection url.
       append url jdbc:oracle:thin
       append url :
       append url $username
       append url /
       append url $password
       append url "@"
       append url $serverName
       append url :
       append url $portNumber
       append url :
       append url $databaseName
       set oraConnection [ java::call DriverManager getConnection $url ]
       set oraDatabaseMetaData [ $oraConnection getMetaData ]
       set oraDatabaseVersion [ $oraDatabaseMetaData getDatabaseProductVersion ]
       puts "Connected to: $url"
       puts "$oraDatabaseVersion"
       return $oraConnection
    proc oracleDisconnect { oraConnect } {
      $oraConnect close
    proc oraJDBCType { oraType } {
      #translation of JDBC types as defined in XOPEN interface
      set rv "NUMBER"
      switch $oraType {
         "0" {set rv "NULL"}
         "1" {set rv "CHAR"}
         "2" {set rv "NUMBER"}
         "3" {set rv "DECIMAL"}
         "4" {set rv "INTEGER"}
         "5" {set rv "SMALLINT"}
         "6" {set rv "FLOAT"}
         "7" {set rv "REAL"}
         "8" {set rv "DOUBLE"}
         "12" {set rv "VARCHAR"}
         "16" {set rv "BOOLEAN"}
         "91" {set rv "DATE"}
         "92" {set rv "TIME"}
         "93" {set rv "TIMESTAMP"}
         default {set rv "OBJECT"}
      return $rv
    proc oracleQuery { oraConnect oraQuery } {
       set oraStatement [ $oraConnect createStatement ]
       set oraResults [ $oraStatement executeQuery $oraQuery ]
       # The following metadata dump is not required, but will be a helpfull sort of thing
       # if ever want to really build an abstraction layer
       set oraResultsMetaData [ $oraResults getMetaData ]
       set columnCount        [ $oraResultsMetaData getColumnCount ]
       set i 1
       puts "ResultSet Metadata:"
       while { $i <= $columnCount} {
          set fname [ $oraResultsMetaData getColumnName $i]
          set ftype [oraJDBCType [ $oraResultsMetaData getColumnType $i]]
          puts "Output Field $i Name: $fname Type: $ftype"
          incr i
       # end of metadata dump
       return $oraResults
    #now to run a quick query and dump the results.
    set oraConn [oracleConnect myserver orcl 1555 scott tiger ]
    set oraRs [oracleQuery $oraConn "select name, count(*) numlines from user_source group by name" ]
    #for each row in the result set
    while {[$oraRs next]} {
      #grab the field values
      set procName [$oraRs getString name]
      set procCount [$oraRs getInt numlines]
      puts "Program unit $procName comprises $procCount lines"
    $oraRs close
    $oraConn close

    Oracle may indeed have used OraTCL as the starting point for OMB+, but if so then they have clearly wrapped their own interface around it and hidden the original commands. Now, I suppose that it should be possible to add OraTcl as an external library, however the Oratcl distribution makes use of the TCL "load" command to load their binaries.
    You will quickly find that Oracle has also disabled the standard TCL "load" command in OMB+, thus making very difficult to add third-party plug-in packages.
    If you can find a pure-TCL script db interface similar to OraTcl to manage SQL*Plus connections that doesn't use any of the TCL commands that ORacle has disabled - well then you could probably get those to load as packages.
    Or, like me, you could just use the supplied java interface and code your own as needed.
    Cheers,
    Mike

  • Running sql from a text item

    Hi.
    I build record groups that display information for the user. These record groups are built on custom SQL that the user can add themselves. As this is open to errors I want to add a "Check Syntax" button.
    All it needs to do is run the query that the user types in and ensure it runs successfully and the required columns are in place. The entire SQL statement is held within a text item.
    If it errors i want to notify the user of the error that sql would produce,
    Any ideas on the best way to acheive this?
    Thanks

    i think with Dynamic SQL u can do this
    Set the query of Text item in a string and execute it using Dynamic query
    Execute immediate syntax
    Any error comes in Dynamic query return it to user
    Baig,
    http://baigsorcl.blogspot.com

  • Remote Execution from Powershell Script called from Team Foundation Build

    Hello
       I am trying to deploy a sharepoint solution with a sharepoint script, with this approach:
    First i test the environment, using windows powershell console
    New-PSSession -ComputerName developmentserver01
    Enter-PSSession -computername developmentserver01
    d:
    cd d:\deploymentscripts
    .\deploysharepoint.ps1
     Then i start the automation:
       1.- TFS runs a build that call at the end to "deploy.ps1" locally in the build server. ---> this is working.
       2.- desploy1.ps1 copy the drop files to the development environment developmentserver01 shared folder.
       3.- after copy the files,  deploy1.ps1 connet with the development environment machine developmentserver01  using remote connection commands from powershell -->this is working.
       4.- this step fails, in this step i try to execute the deployment script deploySharepoint.ps1 that has copied in the development environment machine in the step 2.
         First using commands inside the script like in the powershell console, but i see that the commands are running inside the TFS build machine not in the machine that i connected whit remote connection
    d:
    cd d:\deploymentscripts
    .\deploysharepoint.ps1Later using different options (invoke-command, ...) only this optionk works:
    Invoke-Command -computername developmentserver01 -scriptblock{d:\DeploymentScripts\deploysharepoint.ps1 -solutionNames @("parameter1")}
    The problem it´s that i think that invoke-command don´t work like the commands using powershell console , because the script show the error that the user don´t haver permissions for accesing the Farm of sharepoint. If i run the script with remote session in a power shell console as show at the beginning of the post, all things work fine. How can i run the remote script deploysharepoint.ps1 with remote session from the script desploy.ps1, like using powershell console?

    have you tried passing credentials to it maybe use credssp, you could pass new session to your invoke-command although this shouldnt make difference, i basically think that when you opened this ps session it sees you admin therefore when you do the enter
    session you are still admin, when you use the invoke i am not so sure it keeps your creds..
    $s = New-PSSession -ComputerName developmentserver01
    Invoke-Command -session $s -scriptblock{d:\DeploymentScripts\deploysharepoint.ps1 -solutionNames @("parameter1")}

  • Running SQL Server Function and Procedures from Oracle

    I am trying to run SQL Server 2005 functions and/or procedures from a SQL statement in Oracle. I have gone throught the hetergeneous services and have connected to the SQL Server database successfully. I can also do a query to a table in SQL Server successfully; but I have not been able to execute a procedure or a function.

    Have you tried Oracle syntax? It seems to me that you have only tried T-SQL syntax, e.g. execute proc.
    Wrap it in a begin..end tag like you would a normal PL/SQL function or proc call. Assumption is that as Oracle makes the remote database (via the dblink) look like an Oracle database, you should also play along and pretend it is one and treat it as such.
    E.g.declare
      r integer;
    begin
      -- execute remote proc
      procFoo@dblink( 'ABC' );
      -- call a remote function
      r := funcFoo@dblink( 123 );
    end;

  • Is there a way to get long running SQL Agent jobs information using powershell?

    Hi All,
    Is there a way to get long running SQL Agent jobs information using powershell for multiple SQL servers in the environment?
    Thanks in Advance.
    --Hunt

    I'm running SQL's to fetch the required details and store it in centralized table. 
    foreach ($svr in get-content "f:\PowerSQL\Input\LongRunningJobsPowerSQLServers.txt"){
    $dt = new-object "System.Data.DataTable"
    $cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
    $cn.Open()
    $sql = $cn.CreateCommand()
    $sql.CommandText = "SELECT
    @@SERVERNAME servername,
    j.job_id AS 'JobId',
    name AS 'JobName',
    max(start_execution_date) AS 'StartTime',
    max(stop_execution_date)AS 'StopTime',
    max(avgruntimeonsucceed),
    max(DATEDIFF(s,start_execution_date,GETDATE())) AS 'CurrentRunTime',
    max(CASE WHEN stop_execution_date IS NULL THEN
    DATEDIFF(ss,start_execution_date,stop_execution_date) ELSE 0 END) 'ActualRunTime',
    max(CASE
    WHEN stop_execution_date IS NULL THEN 'JobRunning'
    WHEN DATEDIFF(ss,start_execution_date,stop_execution_date)
    > (AvgRunTimeOnSucceed + AvgRunTimeOnSucceed * .05) THEN 'LongRunning-History'
    ELSE 'NormalRunning-History'
    END) 'JobRun',
    max(CASE
    WHEN stop_execution_date IS NULL THEN
    CASE WHEN DATEDIFF(ss,start_execution_date,GETDATE())
    > (AvgRunTimeOnSucceed + AvgRunTimeOnSucceed * .05) THEN 'LongRunning-NOW'
    ELSE 'NormalRunning-NOW'
    END
    ELSE 'JobAlreadyDone'
    END)AS 'JobRunning'
    FROM msdb.dbo.sysjobactivity ja
    INNER JOIN msdb.dbo.sysjobs j ON ja.job_id = j.job_id
    INNER JOIN (
    SELECT job_id,
    AVG
    ((run_duration/10000 * 3600) + ((run_duration%10000)/100*60) + (run_duration%10000)%100)
    +
    STDEV
    ((run_duration/10000 * 3600) + ((run_duration%10000)/100*60) + (run_duration%10000)%100) AS 'AvgRuntimeOnSucceed'
    FROM msdb.dbo.sysjobhistory
    WHERE step_id = 0 AND run_status = 1
    GROUP BY job_id) art
    ON j.job_id = art.job_id
    WHERE
    (stop_execution_date IS NULL and start_execution_date is NOT NULL) OR
    (DATEDIFF(ss,start_execution_date,stop_execution_date) > 60 and DATEDIFF(MINUTE,start_execution_date,GETDATE())>60
    AND
    CAST(LEFT(start_execution_date,11) AS DATETIME) = CAST(LEFT(GETDATE(),11) AS DATETIME) )
    --ORDER BY start_execution_date DESC
    group by j.job_id,name
    $rdr = $sql.ExecuteReader()
    $dt.Load($rdr)
    $cn.Close()
    $dt|out-Datatable
    Write-DataTable -ServerInstance 'test124' -Database "PowerSQL" -TableName "TLOG_JobLongRunning" -Data $dt}
    You can refer the below link to refer out-datatable and write-dataTable function.
    http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/01/use-powershell-to-collect-server-data-and-write-to-sql.aspx
    Once we've the table details, I'm sending one consolidated email to automatically.
    --Prashanth

  • Listing RDS 2012 R2 collections from powershell remote fails

    I'm trying to list different informations of a RDS server farm => from a remote client PC <=
    I do following but when typing the last command - I get an error.
    Knowing that that same command runs correctly when launched from an RDS server
    enter-pssession RDS-SERVER-XYZ.contoso.net
    import-module remotedesktop
    get-command -module remotedesktop
     Get-RDSessionCollection -ConnectionBroker RDS-BRK-1.contoso.net
     => fails with message :
     Cannot index into a null array.
     At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\remotedesktop\Utility.psm1:54 char:9
     +     if ($_script_resource[$Id])
     +         ~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : NullArray
     Cannot index into a null array.
     At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\remotedesktop\Utility.psm1:54 char:9
     +     if ($_script_resource[$Id])
     +         ~~~~~~~~~~~~~~~~~~~~~~
         + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
         + FullyQualifiedErrorId : NullArray
     Get-RDSessionCollection :
         + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
         + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-RDSessionCollection
    Listing RDS 2012 R2 collections from powershell remote fails / same commandlet from local RDS serevr works fine
    Am I missing something ?
    MCTS Windows Server Virtualization, Configuration

    Are the Windows Remote Management rules enabled on the inbound firewall of the RDSH server?
    If you are running multiple roles on the RDSH  server you may need to increase the size of the memory available for powershell remoting.
    Run Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1000 with powershell as an admin and reboot.
    HTH,
    JB

  • How to execute sql scripts from Powershell across multiple databases

    Re: How to execute sql scripts from Powershell across multiple databases
    I have an tsql script that I want to run across a list of databases. How is the best way to do this in Powershell? Thanks.

    My example below, using just the SMO and not breaking up the batches, the ExecuteWithResults give the following error when the .sql file contains a GO. My script files are as simple as a DECLARE and then a GO.
    WARNING: SQL Script Failed
    The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not in the correct sequence. This is likely caused by a user-specified "format-list" comm
    and which is conflicting with the default formatting.
        + CategoryInfo          : InvalidData: (:) [out-lineoutput], InvalidOperationException
        + FullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand
    Also, when executing from the ISE, is there a way to force the ISE to release the files. I am having to close the ISE and reopen my script every time I want to make a testing change to the .sql file.
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
    $scriptspath = "C:\temp\psExecuteSQLScripts\scripts"
    $SQLServer = "fidevc10"
    $SQLDB = "Bank03"
    # Create SMO Server Object
    $Server = New-Object ('Microsoft.SQLServer.Management.Smo.Server') $SQLServer
    # Get SMO DB Object
    $db = $Server.Databases[$SQLDB]
    # Load All SQL Scripts in Directory
    $scripts = Get-ChildItem -Path (Join-Path $scriptspath "*") -Include "*.sql" -Recurse
    # Loop through each script and execute
    foreach ($SQLScript in $scripts)
    $fullpath = $SQLScript.FullName
    # Read the Script File into Powershell Memory
    $reader = New-Object System.IO.StreamReader($fullpath)
    $script = $reader.ReadToEnd()
    # Execute SQL
    Write-Host "Executing $SQLScript on $SQLDB...."
    try
    $ds = $db.ExecuteWithResults($script)
    Foreach ($t in $ds.Tables)
    Foreach ($r in $t.Rows)
    Foreach ($c in $t.Columns)
    Write-Host $c.ColumnName "=" $r.Item($c)
    Write-Host "Complete"
    catch [Exception]
    Write-Warning "SQL Script Failed"
    echo $_.Exception|format-list -force
    Write-Host " " -BackgroundColor DarkCyan

  • Error while running SQL Developer from a network drive.

    I get following error when I start SQL Developer from an un-mapped network drive
    java.lang.NoClassDefFoundError: oracle/classloader/util/AnnotatedNoClassDefFoundError
         at oracle.dmt.dataminer.mviewer.dtree.DecisionTreeEditorAddin.getEditorWeight(Unknown Source)
         at oracle.ideimpl.editor.EditorAddinRegistry.getAddinsImpl(EditorAddinRegistry.java:182)
         at oracle.ideimpl.editor.EditorAddinRegistry.getAddins(EditorAddinRegistry.java:154)
         at oracle.ideimpl.editor.EditorManagerImpl.getAddins(EditorManagerImpl.java:828)
         at oracle.ideimpl.editor.TabGroupState.loadStateInfo(TabGroupState.java:958)
         at oracle.ideimpl.editor.TabGroup.loadLayout(TabGroup.java:1959)
         at oracle.ideimpl.editor.TabGroupXMLLayoutPersistence.loadComponent(TabGroupXMLLayoutPersistence.java:31)
         at oracle.ideimpl.controls.dockLayout.DockLayoutInfoLeaf.loadLayout(DockLayoutInfoLeaf.java:123)
         at oracle.ideimpl.controls.dockLayout.AbstractDockLayoutInfoNode.loadLayout(AbstractDockLayoutInfoNode.java:631)
         at oracle.ideimpl.controls.dockLayout.AbstractDockLayoutInfoNode.loadLayout(AbstractDockLayoutInfoNode.java:628)
         at oracle.ideimpl.controls.dockLayout.AbstractDockLayoutInfoNode.loadLayout(AbstractDockLayoutInfoNode.java:614)
         at oracle.ideimpl.controls.dockLayout.DockLayout.loadLayout(DockLayout.java:302)
         at oracle.ideimpl.controls.dockLayout.DockLayoutPanel.loadLayout(DockLayoutPanel.java:128)
         at oracle.ideimpl.editor.Desktop.loadLayout(Desktop.java:406)
         at oracle.ideimpl.editor.Desktop.loadLayout(Desktop.java:430)
         at oracle.ideimpl.editor.EditorManagerImpl.init(EditorManagerImpl.java:2022)
         at oracle.ide.layout.Layouts.activate(Layouts.java:814)
         at oracle.ide.layout.Layouts.activateLayout(Layouts.java:195)
         at oracle.ideimpl.MainWindowImpl$6.runImpl(MainWindowImpl.java:728)
         at oracle.javatools.util.SwingClosure$1Closure.run(SwingClosure.java:50)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:199)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    Below I am also attaching the long console log if I run
    \\mt000xvrpt91\tools\SQLDeveloper\sqldeveloper\bin\sqldeveloper.exe
    One thing I noticed in that log is the file path
    file:////mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar
    that is wrong it should be file://///mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar
    ie, 5 "/" after "file:" instead of 4 "/"
    If I run SQL developer after Mapping the network drive to "S" I get following.
    S:\SQLDeveloper\sqldeveloper\bin>sqldeveloper
    Registered TimesTen
    log4j:ERROR setFile(null,true) call failed.
    java.io.FileNotFoundException: S:\SQLDeveloper\sqldeveloper\extensions\oracle.datamodeler\log\datamodeler.log (Access is denied)
    at java.io.FileOutputStream.openAppend(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:177)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:102)
    at org.apache.log4j.FileAppender.setFile(FileAppender.java:273)
    at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:156)
    at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:152)
    at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:247)
    at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:210)
    at org.apache.log4j.xml.DOMConfigurator.findAppenderByName(DOMConfigurator.java:140)
    at org.apache.log4j.xml.DOMConfigurator.findAppenderByReference(DOMConfigurator.java:153)
    at org.apache.log4j.xml.DOMConfigurator.parseChildrenOfLoggerElement(DOMConfigurator.java:415)
    at org.apache.log4j.xml.DOMConfigurator.parseRoot(DOMConfigurator.java:384)
    at org.apache.log4j.xml.DOMConfigurator.parse(DOMConfigurator.java:783)
    at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:666)
    at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:616)
    at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:602)
    at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:460)
    at org.apache.log4j.LogManager.<clinit>(LogManager.java:113)
    at org.apache.log4j.xml.DOMConfigurator.configure(DOMConfigurator.java:697)
    at oracle.dbtools.crest.util.logging.Logger.init(Unknown Source)
    at oracle.dbtools.crest.util.logging.Logger.<init>(Unknown Source)
    at oracle.dbtools.crest.fcp.DataModelerAddin.<clinit>(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:247)
    at oracle.ideimpl.extension.AddinManagerImpl.createAddin(AddinManagerImpl.java:433)
    at oracle.ideimpl.extension.AddinManagerImpl.initializeAddins(AddinManagerImpl.java:212)
    at oracle.ideimpl.extension.AddinManagerImpl.initProductAndUserAddins(AddinManagerImpl.java:128)
    at oracle.ide.IdeCore.initProductAndUserAddins(IdeCore.java:1949)
    at oracle.ide.IdeCore.startupImpl(IdeCore.java:1573)
    at oracle.ide.Ide.startup(Ide.java:703)
    at oracle.ideimpl.DefaultIdeStarter.startIde(DefaultIdeStarter.java:35)
    at oracle.ideimpl.Main.start(Main.java:184)
    at oracle.ideimpl.Main.main(Main.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.ide.boot.PCLMain.callMain(PCLMain.java:62)
    at oracle.ide.boot.PCLMain.main(PCLMain.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.classloader.util.MainClass.invoke(MainClass.java:128)
    at oracle.ide.boot.IdeLauncher.bootClassLoadersAndMain(IdeLauncher.java:189)
    at oracle.ide.boot.IdeLauncher.launchImpl(IdeLauncher.java:89)
    at oracle.ide.boot.IdeLauncher.launch(IdeLauncher.java:65)
    at oracle.ide.boot.IdeLauncher.main(IdeLauncher.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.ide.boot.Launcher.invokeMain(Launcher.java:713)
    at oracle.ide.boot.Launcher.launchImpl(Launcher.java:115)
    at oracle.ide.boot.Launcher.launch(Launcher.java:68)
    at oracle.ide.boot.Launcher.main(Launcher.java:57)
    log4j:ERROR setFile(null,true) call failed.
    java.io.FileNotFoundException: S:\SQLDeveloper\sqldeveloper\extensions\oracle.datamodeler\log\datamodeler.log (Access is denied)
    at java.io.FileOutputStream.openAppend(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:177)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:102)
    at org.apache.log4j.FileAppender.setFile(FileAppender.java:273)
    at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:156)
    at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:152)
    at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:247)
    at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:210)
    at org.apache.log4j.xml.DOMConfigurator.findAppenderByName(DOMConfigurator.java:140)
    at org.apache.log4j.xml.DOMConfigurator.findAppenderByReference(DOMConfigurator.java:153)
    at org.apache.log4j.xml.DOMConfigurator.parseChildrenOfLoggerElement(DOMConfigurator.java:415)
    at org.apache.log4j.xml.DOMConfigurator.parseRoot(DOMConfigurator.java:384)
    at org.apache.log4j.xml.DOMConfigurator.parse(DOMConfigurator.java:783)
    at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:666)
    at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:616)
    at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:602)
    at org.apache.log4j.xml.DOMConfigurator.configure(DOMConfigurator.java:697)
    at oracle.dbtools.crest.util.logging.Logger.init(Unknown Source)
    at oracle.dbtools.crest.util.logging.Logger.<init>(Unknown Source)
    at oracle.dbtools.crest.fcp.DataModelerAddin.<clinit>(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:247)
    at oracle.ideimpl.extension.AddinManagerImpl.createAddin(AddinManagerImpl.java:433)
    at oracle.ideimpl.extension.AddinManagerImpl.initializeAddins(AddinManagerImpl.java:212)
    at oracle.ideimpl.extension.AddinManagerImpl.initProductAndUserAddins(AddinManagerImpl.java:128)
    at oracle.ide.IdeCore.initProductAndUserAddins(IdeCore.java:1949)
    at oracle.ide.IdeCore.startupImpl(IdeCore.java:1573)
    at oracle.ide.Ide.startup(Ide.java:703)
    at oracle.ideimpl.DefaultIdeStarter.startIde(DefaultIdeStarter.java:35)
    at oracle.ideimpl.Main.start(Main.java:184)
    at oracle.ideimpl.Main.main(Main.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.ide.boot.PCLMain.callMain(PCLMain.java:62)
    at oracle.ide.boot.PCLMain.main(PCLMain.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.classloader.util.MainClass.invoke(MainClass.java:128)
    at oracle.ide.boot.IdeLauncher.bootClassLoadersAndMain(IdeLauncher.java:189)
    at oracle.ide.boot.IdeLauncher.launchImpl(IdeLauncher.java:89)
    at oracle.ide.boot.IdeLauncher.launch(IdeLauncher.java:65)
    at oracle.ide.boot.IdeLauncher.main(IdeLauncher.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.ide.boot.Launcher.invokeMain(Launcher.java:713)
    at oracle.ide.boot.Launcher.launchImpl(Launcher.java:115)
    at oracle.ide.boot.Launcher.launch(Launcher.java:68)
    at oracle.ide.boot.Launcher.main(Launcher.java:57)
    ===================================================================
    Console Log if I run
    \\mt000xvrpt91\tools\SQLDeveloper\sqldeveloper\bin\sqldeveloper.exe
    ========================================================================
    Mar 30, 2011 4:36:37 PM javax.ide.extension.spi.DefaultElementContext getMacroValue
    SEVERE: jar:/file:////mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar!/META-INF/extension.xml:22: Unable to find resource bundle class: oracle.ideimpl.db.resource.UIBundle
    Mar 30, 2011 4:36:37 PM javax.ide.extension.spi.DefaultElementContext getMacroValue
    SEVERE: jar:/file:////mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar!/META-INF/extension.xml:23: Unable to find resource bundle class: oracle.ideimpl.db.resource.UIBundle
    Mar 30, 2011 4:36:37 PM javax.ide.extension.spi.DefaultElementContext getMacroValue
    SEVERE: jar:/file:////mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar!/META-INF/extension.xml:26: Unable to find resource bundle class: oracle.ideimpl.db.resource.UIBundle
    Mar 30, 2011 4:36:37 PM javax.ide.extension.spi.DefaultElementContext getMacroValue
    SEVERE: jar:/file:////mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar!/META-INF/extension.xml:26: Unable to find resource bundle class: oracle.ideimpl.db.resource.UIBundle
    Mar 30, 2011 4:36:37 PM javax.ide.extension.spi.DefaultElementContext getMacroValue
    SEVERE: jar:/file:////mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar!/META-INF/extension.xml:43: Unable to find resource bundle class: oracle.ideimpl.db.resource.UIBundle
    Mar 30, 2011 4:36:37 PM javax.ide.extension.spi.DefaultElementContext getMacroValue
    SEVERE: jar:/file:////mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar!/META-INF/extension.xml:46: Unable to find resource bundle class: oracle.ideimpl.db.resource.UIBundle
    Mar 30, 2011 4:36:37 PM javax.ide.extension.spi.DefaultElementContext getMacroValue
    SEVERE: jar:/file:////mt000xvrpt91/tools/SQLDeveloper/ide/extensions/oracle.ide.db.jar!/META-INF/extension.xml:50: Unable to find resource bundle class: oracle.ideimpl.db.resource.UIBundle
    Mar 30, 2011 4:36:38 PM javax.ide.extension.spi.SAXManifestParser$Handler endElement
    SEVERE: jar:/file:////mt000xvrpt91/tools/SQLDeveloper/sqldeveloper/extensions/oracle.sqldeveloper.jar!/META-INF/extension.xml:316: Exception processing manifest: oracle.classloader.util.AnnotatedNoClassDefFoundError:
    Missing class: oracle.dbtools.raptor.controls.grid.IRaptorGridModel
    Dependent class: oracle.dbtools.raptor.controls.grid.IResultSetTableModel
    Loader: ide-global:11.1.1.0.0
    Code-Source: //mt000xvrpt91/tools/SQLDeveloper/sqldeveloper/extensions/oracle.sqldeveloper.jar
    Configuration: extension jar in \\mt000xvrpt91\tools\SQLDeveloper\sqldeveloper\extensions
    The missing class is not available from any code-source or loader in the system.
    oracle.classloader.util.AnnotatedNoClassDefFoundError:
    Missing class: oracle.dbtools.raptor.controls.grid.IRaptorGridModel
    Dependent class: oracle.dbtools.raptor.controls.grid.IResultSetTableModel
    Loader: ide-global:11.1.1.0.0
    Code-Source: //mt000xvrpt91/tools/SQLDeveloper/sqldeveloper/extensions/oracle.sqldeveloper.jar
    Configuration: extension jar in \\mt000xvrpt91\tools\SQLDeveloper\sqldeveloper\extensions
    The missing class is not available from any code-source or loader in the system.
    at oracle.classloader.PolicyClassLoader.defineClass(PolicyClassLoader.java:2387)
    at oracle.classloader.PolicyClassLoader.findLocalClass(PolicyClassLoader.java:1546)
    at oracle.classloader.SearchPolicy$FindLocal.getClass(SearchPolicy.java:226)
    at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119)
    at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoader.java:1728)
    at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java:1689)
    at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java:1674)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
    at oracle.classloader.PolicyClassLoader.defineClass(PolicyClassLoader.java:2364)
    at oracle.classloader.PolicyClassLoader.findLocalClass(PolicyClassLoader.java:1546)
    at oracle.classloader.SearchPolicy$FindLocal.getClass(SearchPolicy.java:226)
    at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119)
    at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoader.java:1728)
    at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java:1689)
    at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java:1674)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
    at oracle.classloader.PolicyClassLoader.defineClass(PolicyClassLoader.java:2364)
    at oracle.classloader.PolicyClassLoader.findLocalClass(PolicyClassLoader.java:1546)
    at oracle.classloader.SearchPolicy$FindLocal.getClass(SearchPolicy.java:226)
    at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119)
    at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoader.java:1728)
    at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java:1689)
    at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java:1674)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:169)
    at oracle.dbtools.raptor.controls.grid.RSTModelHook$ProviderChildVisitor.end(RSTModelHook.java:64)
    at javax.ide.extension.spi.SAXManifestParser$Handler.endElement(SAXManifestParser.java:138)
    at oracle.xml.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1359)
    at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:376)
    at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:322)
    at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:226)
    at javax.ide.extension.spi.SAXManifestParser.parse(SAXManifestParser.java:87)
    at javax.ide.extension.spi.SAXManifestParser.parse(SAXManifestParser.java:57)
    at javax.ide.extension.ExtensionRegistry.loadExtension(ExtensionRegistry.java:295)
    at oracle.ideimpl.extension.ExtensionManagerImpl.loadExtension(ExtensionManagerImpl.java:701)
    at javax.ide.extension.ExtensionRegistry.loadExtensions(ExtensionRegistry.java:275)
    at oracle.ideimpl.extension.ExtensionManagerImpl.loadExtensions(ExtensionManagerImpl.java:612)
    at javax.ide.extension.ExtensionRegistry.loadExtensions(ExtensionRegistry.java:171)
    at oracle.ideimpl.extension.ExtensionManagerImpl.loadExtensions(ExtensionManagerImpl.java:510)
    at javax.ide.extension.ExtensionRegistry.initialize(ExtensionRegistry.java:381)
    at oracle.ideimpl.extension.ExtensionManagerImpl.initialize(ExtensionManagerImpl.java:954)
    at javax.ide.Service.getService(Service.java:68)
    at javax.ide.extension.ExtensionRegistry.getExtensionRegistry(ExtensionRegistry.java:400)
    at oracle.ide.ExtensionRegistry.getExtensionRegistry(ExtensionRegistry.java:191)
    at oracle.ide.IdeCore.startupImpl(IdeCore.java:1384)
    at oracle.ide.Ide.startup(Ide.java:703)
    at oracle.ideimpl.DefaultIdeStarter.startIde(DefaultIdeStarter.java:35)
    at oracle.ideimpl.Main.start(Main.java:184)
    at oracle.ideimpl.Main.main(Main.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.ide.boot.PCLMain.callMain(PCLMain.java:62)
    at oracle.ide.boot.PCLMain.main(PCLMain.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.classloader.util.MainClass.invoke(MainClass.java:128)
    at oracle.ide.boot.IdeLauncher.bootClassLoadersAndMain(IdeLauncher.java:189)
    at oracle.ide.boot.IdeLauncher.launchImpl(IdeLauncher.java:89)
    at oracle.ide.boot.IdeLauncher.launch(IdeLauncher.java:65)
    at oracle.ide.boot.IdeLauncher.main(IdeLauncher.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at oracle.ide.boot.Launcher.invokeMain(Launcher.java:713)
    at oracle.ide.boot.Launcher.launchImpl(Launcher.java:115)
    at oracle.ide.boot.Launcher.launch(Launcher.java:68)
    at oracle.ide.boot.Launcher.main(Launcher.java:57)
    And more........... I exceeded 30000 character limit at this form

    I am OK to ignore the error. But better option will be SQL Developer take care of this situation.
    My intention is to keep SQL Developer on a readonly share folder and send the path to end users.
    Ideally I wish I could use UNC path so that I dont have to worry about the drive mapping.

  • VBScript Runs Correctly From Command Prompt, But Not From SQL Server Agent Job

    I'm trying to run this script on my local machine to do some post-batch cleanup and it doesn't run correctly from the scheduled job (or when I invoke the job).
    Here's the script in question:
    Option Explicit
    Const filePath = "C:\Documents and Settings\jmunn\My Documents\Visual Studio 2008\Logs\"
    Const holdDays = 6
    main
    Sub Main()
    ClearArchive
    End Sub
    Sub ClearArchive()
    Dim fso 'As Scripting.FileSystemObject
    Dim fld 'As Scripting.Folder
    Dim f 'As Scripting.File
    Dim delLogName, delLogOut, delCtr
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder(filePath)
    delLogName = filePath & "Nightly Backup - Backup Logs Deleted" & ".txt"
    Set delLogOut = fso.CreateTextFile(delLogName, True)
    delLogOut.WriteLine(delLogName)
    delLogOut.WriteLine("")
    delLogOut.WriteLine("-- The following log files were deleted on " & DateValue(Now()) & " at " & TimeValue(Now()))
    delLogOut.WriteLine("")
    delCtr = 0
    For Each f In fld.Files
    If Left(f.Name, 48) = "Nightly Backup - SQL Server Databases_Subplan_1_" And Right(LCase(f.Name), 4) = ".txt" Then
    If DateDiff("d", f.DateCreated, Date()) > holdDays Then
    delLogOut.WriteLine(f.Name)
    fso.DeleteFile f, True
    delCtr = delCtr + 1
    End If
    End If
    Next
    If delCtr = 0 Then
    delLogOut.WriteLine("No log files were deleted this run...")
    End If
    Set fld = Nothing
    Set fso = Nothing
    delLogOut.Close
    End Sub
    If I put the script in its own file and run it from the command prompt, it runs just fine. If the script runs from the SQL Server Agent job, the for-loop will delete the files correctly, but the filenames
    do not get written to the deletion log file and the counter does not get incremented, so according to the job log, nothing was deleted. Why does the script run differently from each invocation? It can't be a permission thing, the service that logs in has full
    access to the directory and the files do get deleted. Any ideas out there?
    Between this and other outstanding issues, I'm quickly losing faith in SQL Server.  >=o(
    Thanks in advance for your thoughts!
    John
    Version Info:
    Microsoft SQL Server Management Studio      10.0.2531.0
    Microsoft Analysis Services Client Tools      10.0.1600.22
    Microsoft Data Access Components (MDAC)      3.85.1132
    Microsoft MSXML      2.6 3.0 4.0 5.0 6.0
    Microsoft Internet Explorer      8.0.6001.18702
    Microsoft .NET Framework      2.0.50727.3603
    Operating System      5.1.2600
    "A bus station is where a bus stops. A train station is where a train stops. On my desk I have a workstation..."

    Hi
    jrmunn
    i am trying to execute VB script to refresh my excel files.. using Vbscript file through SQL Agent job step.
    i have copied VBscript in a file with the extension RefreshExcel.vbs kept in C:\RefreshExcel.vbs
    Below is the script used inside the file (RefreshExcel.vbs)
    //---Script code-----------------------------------------------------------------
    Dim objXL, objWB
    Dim FileLocation, FileName
    On Error Resume Next
    'lgnConn = 1
    FileLocation = "F:\Reports\Reports"
    Set objXL = CreateObject("Excel.Application")
    objXL.DisplayAlerts = False
    FileName = "ReportFile1.xlsx"
    'MsgBox (FileLocation & "/" & FileName)
    Set objWB = objXL.Workbooks.Open(FileLocation & "/" & FileName)
    objWB.EnableConnections
    objXL.CalculateUntilAsyncQueriesDone
    objWB.RefreshAll
    objXL.CalculateUntilAsyncQueriesDone
    objWB.RefreshAll
    objXL.CalculateUntilAsyncQueriesDone
    objWB.Save
    objWB.Close
    Set objWS = Nothing
    Set objWB = Nothing
    objXL.Quit
    Set objXL = Nothing
    'MsgBox ("Refresh Completed")
    ---------------------------------------------------------------------------------------------------//Script complete
    Now when i am trying to call this script file in SQL agent job step (as you mentioned )
    as Type -cmdExec(OperatingSystem)
    cscript "C:\RefreshExcel.vbs"
    Issue: job step executed succesfully ,,but without performing any refresh on the excel. So i am not understandig what is going wrong. the same script file work when i am calling it through a batch file (window scheuler task). But it doesnt support
    to run the file "when user is not logged in"
    that is why  i want to refresh my excel file through sql agent ,which can be scheduled to any time and cab be run as SQL agent credentials.
    Can you please help me on this ...i have tried all the option but nothing working .. found hope by seeing your solution.
    Thanks in advance.
    Please help me. :-(

  • Running  sql scripts from different directory

    Hi
    I have sql scripts in different directories as follows:
    D:\myapp\sql
    - load.sql
    - init.sql
    D:\myapp\sql\schema
    -users.sql
    -structure.sql
    D:\myapp\sql\populate\
    - data1.sql
    - data2/sql
    load.sql call all the other scripts as below:
    @init.sql
    @schema\users.sql
    @schema\structure.sql
    @populate\data1.sql
    @populate\data2.sql
    All my scripts run correctly when I run load.sql from D:\myapp\sql on comand prompt.
    I need a way to run this script from a different directory say D:\ or C:\
    I am writing a installer which will execute from a different directory.
    Right now I get a file not found error for scripts within schema an populate folder.
    Please let me know how can I make this work from a different directory.
    Thanks
    kelvin

    Hi peter. i think you cannot run files spread across different locations.
    --the method which u specified always looks to the defined path                                                                                                                                                                                                                                                                                       

  • How to run .sql file in tsql or powershell

    Hi All,
    HOw to run .sql file inside the TSQL or powershell using with IF else condition. This below query works fine but when i executing through the SQL Agent it's geeting an error.Please could help how to run through the SQL agent already using execution type
    in agent as 'Operating system(CmdExec)'
    Declare @computerName varchar(100), @InstanceName varchar(50)                             
    SET @ComputerName = REPLACE(CAST(SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS varchar),'\','$')  
    SET @InstanceName = REPLACE(CAST(SERVERPROPERTY('instancename') AS varchar),'\','$')
    IF (@InstanceName = 'SQL2008R2')
    Begin  
    :r C:\BackupFolder\Test1.sql    
    :r C:\BackupFolder\Test2.sql    
    End
    IF (@InstanceName = 'SQLINS2')
    BEGIN
    :r C:\BackupFolder\Test3.sql
    END
    IF (@InstanceName = 'SQL2012')
    BEGIN
    :r C:\BackupFolder\Test4.sql
    END
    Thansk in Advance
    A-ZSQL

    In T-SQL, you can try using sqlcmd to invoke sql file
    if @@SERVERNAME='abcd'
    begin
    Master..xp_cmdshell 'sqlcmd -S <ServerName> -i BackupDetails.sql -E'
    end
    OR 
     PowerShell 
    Load the snapins
    Add-PSSnapin SqlServerCmdletSnapin100
    Add-PSSnapin SqlServerProviderSnapin100
    Function Get-SqlInstances {
    Param($ServerName = '.')
    $localInstances = @()
    [array]$captions = gwmi win32_service -computerName $ServerName | ?{$_.Name -match "mssql*" -and $_.PathName -match "sqlservr.exe"} | %{$_.Caption}
    foreach ($caption in $captions) {
    if ($caption -like "MSSQLSERVER") {
    $localInstances += $ServerName
    } else {
    $temp = $caption | %{$_.split(" ")[-1]} | %{$_.trimStart("(")} | %{$_.trimEnd(")")}
    $localInstances += "$ServerName\$temp"
    $localInstances
    $instance=Get-SqlInstances -ServerName HQDBSP17
    foreach($i in $instance)
    if($i -like 'CRM2011')
    write-host 'CRM Database'
    invoke-sqlcmd -inputfile 'F:\PowerSQL\test.sql' -ServerInstance 'abcd'
    if( $i -like 'SQL2012')
    write-host 'SQL 2012 instance'
    invoke-sqlcmd -inputfile 'F:\PowerSQL\test.sql' -ServerInstance 'abcd'
    --Prashanth

Maybe you are looking for