簡體   English   中英

從.bat文件執行.ps1文件

[英]Executing a .ps1 file from a .bat file

我有一個.bat文件,該文件可以執行所有問題的列表。 它到達powershell執行行:PowerShell.exe“ Y:\\ Data \\ FS01 \\ NoTouch_Deploy.ps1”

我收到以下錯誤:警告:無法加載“ SQLAS”擴展名:嘗試管理服務時SMO中的異常。 ->無法檢索此請求的數據。 ->無效的班級

當我通過GUI運行相同的腳本時,它運行沒有問題。 我也嘗試過並在同一位置運行一個簡單的Powershell腳本(測試人員只是拋出一個Windows消息框,讓我知道它正在打開並執行),這同樣可行。 但是一旦我添加了常規.ps1並從.bat文件運行它,我就會收到此錯誤。 該腳本包含在下面。 腳本快速摘要:它設置了幾個變量,創建了2個函數(BCP和用於錯誤捕獲的日志寫入),重命名了某些表並觸發了SQL存儲過程。 然后執行BCP功能以在服務器之間移動數據,然后再執行一個過程。

cls

[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
## TEST MSGBOX## [System.Windows.Forms.MessageBox]::Show("We are proceeding with next step." , "Status") 
$ErrorActionPreference = "stop"
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
[Void][System.Reflection.Assembly]::LoadWithPartialName("System.Data")
Add-PsSnapin sqlserverprovidersnapin100 -ErrorAction SilentlyContinue
Add-PsSnapin sqlservercmdletsnapin100 -ErrorAction SilentlyContinue
Import-Module SQLPs -DisableNameChecking -ErrorAction SilentlyContinue
#Import-Module SQLAS    -DisableNameChecking -ErrorAction SilentlyContinue
Set-Location 'C:\'
# Set Variables (Make table driven for final tool creation)
$SourceServer = "DevServ"
$SourceDB = "DevDB"
$SourceObject = "DevTable"
$TargServer = "ProdServ"
$TargDB = "ProdDB"
$TargObject = "ProdTable" 
$ContainerDB =  'MainDB'

################################################################################################################
##                                      Begin Function LogWrite                                              ##
##################################################################################################### ###########
Function LogWrite ()
    {
        Param
            (

                [string]$LogStr,
                [string]$Table,
                [string]$Server,
                [string]$DataBase
            )

        Trap{continue} 
        #$DateTime = Get-Date -UFormat "%Y:%MM:%D:%H:%M:%S"

        $LogInsQuery = "INSERT INTO dbo.Deploy_LOG ([TableName], [LOGTEXT],[DateStamp]) VALUES ('" + $Table + "', '" + $LogStr + "',getdate())"
         Invoke-Sqlcmd -ServerInstance $SServer -Database $SDB -Query $LogInsQuery

    }
################################################################################################################
##                                      Begin Function BCP
################################################################################################################


Function BCP ()
    {
        Param
            (
                [string]$SourceServer,
                [string]$SourceDB,
                [string]$SourceObject,
                [string]$TargServer,
                [string]$TargDB,
                [string]$TargObject
            )
        $NewServer

        Try
            {
                $SourceCon = New-Object Data.SqlClient.SqlConnection
                $SourceCon.ConnectionString = "Data     Source=$SourceServer;DataBase=$SourceDB;Integrated Security=True"

                Logwrite  "$TargObject -- Beginning BCP transfer process" $SourceObject

                $TargCon = New-Object Data.SqlClient.SqlConnection
                $TargCon.ConnectionString = "Data Source=$TargServer;DataBase=$TargDB;Integrated Security=True"
                $TargCon.open()

                #[long]$StartCount = (Invoke-Sqlcmd -ServerInstance $SourceServer -Query "SELECT COUNT(*) as 'Ct' FROM $TargDB.dbo.$TargObject")[0]

                $bcp = New-Object Data.SqlClient.SqlBulkCopy($TargCon.ConnectionString, [System.Data.SqlClient.SqlBulkCopyOptions]::KeepIdentity)

                $FieldsServer = New-Object "Microsoft.SqlServer.Management.SMO.Server" $TargServer
                $DevServer = New-Object "Microsoft.SqlServer.Management.SMO.Server" $SourceServer

                $SelectString = 'SELECT '
                $DevServer.Databases[$TargDB].Tables | ?{$_.name -eq $TargObject} | %{$_.Columns | %{$SelectString += "[$($_.name)],"}}
                $SelectString = $SelectString.Substring(0, ($SelectString.Length - 1)) # Remove the trailing comma
                $SelectString += " FROM dbo.$SourceObject"

                $SourceCon.open()
                $SqlCmd = New-Object "Data.SqlClient.SqlCommand" -ArgumentList $SelectString, $SourceCon
                [Data.IDataReader]$DataReader = $SqlCmd.ExecuteReader()

                $bcp.BulkCopyTimeout = 0
                $bcp.DestinationTableName = "dbo.$TargObject"
                $bcp.WriteToServer($DataReader)

                $SqlCmd = $null
                $DataReader = $null                                     
                $SourceCon.Close()
                $bcp.Close()

                $TargCon.Close()

                LogWrite  "$TargObject -- Transfer complete" $SourceObject;
             }
        Catch
            {
                LogWrite "ERROR in BCP Subroutine -- $_" $SourceObject;
            }

    }

################################################################################################################
##                                      Begin main code section end of functions    
################################################################################################################

Try
             {

    $SqlQuery = "SP_Rename 'TableName','TableName_Deploy'"
    Invoke-Sqlcmd -ServerInstance $SServer -Database $SDB -Query $SqlQuery
    $SqlQuery =""

# runs the Sproc on the FLD server to make sure that the _Deploy table exists, is empty and is indexed. 
    $DeployTableSproc = "EXECUTE  [dbo].[SP_NoTouch_Staging_Build]"
    Invoke-Sqlcmd -ServerInstance $TargServer -Database $ContainerDB -Query $DeployTableSproc

# Runs the BCP process to copy the records to the Feild into the new prepared table. 
BCP $SServer $SDB $SourceObject $TargServer $TargDB $TargObject


    $SqlQuery = "EXECUTE [MainDB].[dbo].[Notify_NoTouch] @EmailType =  6"
    Invoke-Sqlcmd -ServerInstance $SServer -Database $SDB -Query $SqlQuery
    $SqlQuery =""


LogWrite  "No touch table transfer complete Table renamed and indexed" $SourceObject;

            }
        Catch
            {
                LogWrite "ERROR in Transfer process" $SourceObject;
            }

我試圖添加#Import-Module SQLAS -DisableNameChecking -ErrorAction SilentlyContinue,它沒有幫助。 有任何想法嗎? 謝謝

由於您最終希望通過任務計划程序運行此腳本,因此我將繼續在要使用它的服務器上創建任務。 在“操作”選項卡中,只需設置以下條件:

程序/腳本字段

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe

添加參數字段:

-NoProfile -ExecutionPolicy unrestricted -nologo -command "&{\\path\to\your\files\FileName.ps1 -Silent:$true}"

如果要使用批處理文件進行測試,則只需輸入以下代碼:

schtasks /RUN /s "ServerName" /TN "Scheduled Tasks Named" | Out-String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM