Powershell script as a step in sql job giving error - sql

I am trying to create a sql job which syncs users from a csv file to ad group.
My powershell script is one of the steps of this job. Issue is that my script is supposed to run on another server which has Active Directory but i keep on getting error when i run this step.
My script is following:
invoke-Command -Session Server-Name
Import-Module activedirectory
$ADUsers = Import-csv \\Server-Name\folder\file.csv
foreach ($User in $ADUsers)
{
$Username = $User.sAMAccountName
$group=$user.adgroup
if (Get-ADUser -F {SamAccountName -eq $Username})
{
foreach($group in $groups){Add-ADGroupMember -identity $group -Members $Username}
Write-Output "$username has beeen added to group $group"
}
}
Error i am getting is
Executed as user: Username. A job step received an error at line 2 in a PowerShell script. The corresponding line is 'Invoke-Command -Session Server-Name. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot bind parameter 'Session'. Cannot convert the "Server-Name" value of type "System.String" to type "System.Management.Automation.Runspaces.PSSession". '. Process Exit Code -1. The step failed.
server name has '-' in between so need to know if that is causing the issue
or i am using wrong way to run this script on a different server from a sql job
Any help would be appreciated!

Jaspreet I am not expert on powershell but seems like you are passing the wrong parameters.Just referring to Microsoft docs seems like you need to pass the computer name rather than -Session
Try with this line of code at starting
invoke-Command -ComputerName Server-Name.
For more please refer Microsoft docs
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-6#examples

Related

SP2-0734: unknown command beginning select

I have continuous automated application deployment building on Azure DevOps server 2019(ex TFS). Part of deploy is checking the Oracle DB status, before running scripts, the script below works for a year, and ones (probably after latest Azure DevOps server update 2019.1) it stops working with an error:
SQL> SP2-0734: unknown command beginning " select..." - rest of line ignored.
SQL> SP2-0734: unknown command beginning " select..." - rest of line ignored.
$chekdbsql = 'select status from v$instance;'
$i = 1
$chkdb = ""
while ($chkdb.Contains("OPEN") -ne 'True') {
Clear-Variable -Name chkdb
$chkdb = ($chekdbsql | cmd /c "sqlplus -s user/password#localhost/ora as sysdba")
if ($chkdb.Contains("OPEN") -eq 'True'){
break
}
echo "Trying to connect to database. Attempt $i"
sleep 10
$i++ }
write-host "Connected! Database's status is 'open'." -ForegroundColor green
If I tried to execute command locally on the machine where the application is built - it's work well.
The space before select makes me think it's a character encoding issue. See e.g. this, this
beginning " select..."
I'm not familiar enough with powershell to know what the problem is. I can think of a workaround, but it's a bit of a hack.
$chekdbsql = "`nselect status from v`$instance;"
This makes sure that whatever garbage characters are getting inserted at the beginning of the string will be on their own line in SQL*Plus. So if you get a SP2-0734, your select command will still run after that. Since it's now a double-quoted string, I escaped the $.

Powershell process wait for SQL query to complete

I have a Powershell script that runs daily. The script is supposed to run a SQL query and create a file with the results.
Import-Module SqlPs
Invoke-Sqlcmd -InputFile "C:\SQL Queries\dailyexport1pm.sql" | Out-File -filepath "I:\HTPN Training and Workflow\Daily Epic Completion\$(get-date -f yyyy-MM-dd)dailyexport1pm.txt"
This used to work, however we recently added a large amount of data that causes the query to take up to 3.5 minutes. I do not have a strong understanding of powershell and need to have the out-file process run once the SQL query is complete. Any assistance would be appreciated.
The script outputs a blank txt file. When I check the task scheduler last run result, that the powershell script is the only action of, it says "The operation completed successfully. (0x0)"
I think there might be some error in the sql-file. Requesting you to try this once:
$Error.Clear()
try {
Import-Module SqlPs
Invoke-Sqlcmd -InputFile "C:\SQL Queries\dailyexport1pm.sql" -WarningAction SilentlyContinue -OutputSqlErrors $false
}
catch {
$Error | out-file -filepath "C:\temp\SqlLog.txt"
}
Note: Later if you see no error and the output is coming properly then you can pipe it to 'Out-File -filepath "I:\HTPN Training and Workflow\Daily Epic Completion\$(get-date -f yyyy-MM-dd)dailyexport1pm.txt" '
Hope it helps.

VB.net and powershell variables

I have a Visual Studio form running with VB.net and I'm collecting info needed to setup an AD user. In the end, this info will need to simply be passed to Powershell with no return info needed. Before that though, I need it to check if a printer code has already been assigned to someone before allowing it to be submitted to another user. I have a simple powershell script written up for it.
(We use the Pager field to store the printer code.)
Import-Module ActiveDirectory
$Page = $args[0]
Get-ADUser -Filter { Pager -like $Page } | FT Name
I setup the code I found HERE, and attempted to modify it to my script but it keeps crashing on
Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
It gives me: An unhandled exception of type 'System.Management.Automation.ParseException' occurred in System.Management.Automation.dll
If I run his little 6+5 basic example script, it works, but when I try to retrieve info and return a name, it doesn't like it. How can I get it to return the name of the person if it find it? And since it won't run, I'm not even sure if passing the printer code as $args[0] is going to work yet.
Your results is expecting a collection of PowerShell objects. When you pipe the Get-ADUser command to Format-Table, it effectively strips the object down to a stream of strings. Try without the | FT Name.
Import-Module ActiveDirectory #if you're using powershell 3 or later, this may be redundant
# $Page = $args[0] # don't need to do this
$results = Get-ADUser -Filter { Pager -like $args[0] }
Write-Verbose $results
#Write-Verbose $results.Name #try this if the above one works
Update:
Write-Verbose may be causing an issue.
Try this:
Get-ADUser -Filter { Pager -like $args[0] }
Just that one line as the total PS code. (Assuming you have PowerShell 3.0 or later, you don't need Import-Module) That line will return objects of type TypeName: Microsoft.ActiveDirectory.Management.ADUser (from `Get-ADUser username | Get-Member).
You may also be able to use the .Net object type directly, without PowerShell. I'm not knowledgeable about .NET beyond what I picked up working with PowerShell.
Accessing AD using .NET, info from MSDN.

Looping a powershell script

This might seem like an easy question but I had to ask. I have a powershell script that calls another script and it patches a SQL database. Normally you can just patch all databases at once, but sometimes that halts and you have to cancel it and do single datasbases instead. Here is the script I made to do this sqlps is already run prior to this code segment:
do {
$dabname = Read-Host "Enter the database name or (stop) to end"
if($dabname -ne "stop") {
$sclient = Read-Host "Enter Client name"
$date = Get-Date -Format "yymmdd"
$sqlsrvname = Read-Host "Please enter the sql server name"
SQL-remote -DBServer $sqlsrvname -DBNameList $dabname –client $sclient –mainline HTFS –datefolder $date –targetenv $sqlsrvname}
}until($dabname -eq "stop")
but it keeps telling me the server doesnt exist, I cant figure out what I did wrong can someone please tell me whats missing? This script its suppose to; once working; keep asking if you want to patch more databases after patching them until you say "stop." The sql-remote is a function in which the sql patch script is stored.

How to route SQL print output to log file?

Anyone who knows how to route print ' ' in an sql script to a logfile when using Invoke-Sqlcmd?
I tried using sqlcmd -o someoutfile.txt, but it overwrites, it does not append to existing file. And if an SQL error occurs, only the error message is sent to file, not the print ' '.
When using Invoke-Sqlcmd | out-file someoutfile.txt -Append, it appends only Write-Output and eventually SQL errors, but not the print ' ' in the sql script excuted.
Has anyone found a solution for this?
Invoke-SqlCmd implements T-SQL PRINT statements and RAISERROR using the verbose parameter. To capture verbose output, first you'll need to include the parameter in your call to invoke-sqlcmd i.e. invoke-sqlcmd -verbose and next you can do one of two things:
If you're using Powershell V3 or higher you can redirect verbose output:
invoke-sqlcmd -verbose 4>&1 | outfile someoutfile.txt
If you're using Powershell V2 you can't redirect verbose output to a file, however you can use start-transcript to send all screen output to a file. One gotcha with this approach--it will not work with SQL Agent Powershell job step. It will however work with a cmdexec job step which calls powershell.exe.
And one moment...
The command "Invoke-Sqlcmd" has a parameter -SeverityLevel.
SeverityLevel specifies the lower limit for the error message severity level Invoke-Sqlcmd returns to the ERRORLEVEL PowerShell.
Invoke-Sqlcmd does not report severities for informational messages that have a severity of 10!
Severity Level 10: Status Information
This is an informational message that indicates a problem caused by mistakes in the information the user has entered. Severity level 0 is not visible in SQL Server.