我們創建了運行特定文件夾中所有腳本的powershell腳本。PowerShell腳本無法進行Windows身份驗證
$server = Read-Host -Prompt 'Please enter server name'
$usrname = Read-Host -Prompt 'Please enter user name'
$passwd = Read-Host -Prompt 'Please enter password' -assecurestring
$dbname = Read-Host -Prompt 'Please enter DB name'
$ScriptFolder = Read-Host -Prompt 'Please enter the folder path'
$passwd =[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwd))
$logfile = "$ScriptFolder"+"\Scripts_Log_"+(Get-
Date).ToString("yyyyMMdd")+".txt"
"$(Get-Date) : Queries to be executed for Database $dbname on $server " >> $logfile
try{
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$server;Database=$dbname;trusted_connection=true;User ID=$usrname;Password=$passwd;"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
foreach ($query in Get-ChildItem -path $ScriptFolder -Filter *.sql)
{
$qu = Get-Content $query.FullName
try{
$command = $SqlConnection.CreateCommand()
$command.CommandText = $qu
$Reader = $Command.ExecuteReader()
$Reader
"$(Get-Date) : $query - Successfully executed`n" >> $logfile
write-host "$query - Successfully executed`n" -foregroundcolor "Green"
$Reader.close()
}
catch{
write-host "Unable to execute - $query :" -foregroundcolor "Red"
write-host "$_.Message`n" -foregroundcolor "Red"
"$(Get-Date) : $query - Script failed due to:" >> $logfile
"$_.Message`n" >> $logfile
}
}
}
catch{
write-host "Login failed:" -foregroundcolor "Red"
write-host "$_.Message`n" -foregroundcolor "Red"
"$(Get-Date) : login failedn:" >> $logfile
"$_.Message`n" >> $logfile
}
$SqlConnection.Close()
write-host "All the process has been completed" -foregroundcolor "Yellow"
"$(Get-Date) : All the process has been completed" >> $logfile
但是當這個腳本,數據庫服務器上運行,我有Windows身份驗證,那麼它沒有做裏面的東西每個循環和不失敗任。有沒有一種方法,這個腳本將同時適用於Windows和SQL身份驗證
所以,當你想要的東西沒有做,那還有什麼它實際上做什麼?有錯誤嗎?要調試的東西,這是不夠的,說它不是你想要的。瞭解它**正在做什麼很重要。爲了回答你最後的問題,你的連接字符串決定了用戶的認證方式。如果您包含trusted_connection選項,那麼您將獲得 - 用戶標識和密碼將被忽略。所以要使用sql認證,你必須離開那一點。 – SMor
@SMor我明確告訴它,它不會進入每個循環,只是移出循環 – DevelopmentIsMyPassion