我们创建了运行特定文件夹中所有脚本的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