Looping a powershell script - sql

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.

Related

Color coding Invoke-SQL in Powershell

Using invoke-sql I have a PowerShell script that returns results from a SQL Query. That query has the status of several data points local I want to colour code the entire row if the column of Status returns different values. Is this possible as I know you can colour code Charts in PowerShell but not sure how a larger return query would work?
param(
[string] $dataSource = "SQLName",
[string] $database = "DatabaseName",
[string] $sqlCommand = $("Select tbldatafeed.datafeed_name,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(tbldatafeedhistory.status_id,1,'Running'),2,'Completed'),3,'Faulted'),4,'Warning'),5,'Terminating'),6,'Terminated'),7,'Pending') AS Status,DateDiff(MINUTE,tbldatafeedhistory.start_time, tbldatafeedhistory.end_time) As 'Run Time(minutes)'
from tblDataFeedHistory
left Join tblDatafeed on tbldatafeedhistory.datafeed_id = tbldatafeed.datafeed_id
inner join
(
Select max(start_time) as LatestDate, [datafeed_id]
from tblDataFeedHistory
Group by datafeed_id
) SubMax
on tblDataFeedHistory.start_time = SubMax.LatestDate
and tblDataFeedHistory.datafeed_id = SubMax.datafeed_id
WHERE tbldatafeed.is_active = 1
Order by tbldatafeed.datafeed_id")
)
$connectionString = "Data Source=$dataSource; " + "Integrated Security=SSPI; " + "Initial Catalog=$database"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
write-output $adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables
}
$FeedID = Invoke-SQL
$FeedID
The output would be a red highlighted line if the column returned Failed, yellow if the Column returns Warning, Green if the column returns Completed.
I've not personally found or seen a reason to do this with SQL data generally, nor do I have any record in my stash of anyone who has.
Anything you write to the screen can have color. It's one of the primary focuses of the …
[Write-Host][1]
Or
[Console]::ForegroundColor]
... cmdlet or .Net class.
However, if you plan to use that data on the pipeline, or elsewhere, then don't use it. Especially if you are not on the newest PowerShell versions. Legacy PowerShell, Write-Host empties the buffer, later PowerShell versions, send it to the Information Stream. As talked by PowerShell inventor Jeffery Snover here:.
http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful
... Jeffrey Snover change his stance on this as of May 2016.
With PowerShell v5 Write-Host no longer "kills puppies". data is
captured into info stream ...
https://twitter.com/jsnover/status/727902887183966208
https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Write-Information?view=powershell-5.1
However, there are PowerShell modules you can leverage to get really creative with color.
Find-Module -Name '*color*' | Format-Table -AutoSize
You also have several scripts to leverage as is or tweak for your use case.
Format Table Colors in PowerShell
Format the output table colors in PowerShell host with/without conditional colorful formatting.
Download : Write-PSObject.ps1
You do have another option. If you want to call attention, with color to a given screen output line, you can use the ...
Write-Warning
Write-Error
... cmdlets and just accept its default color.
Yet, your question could almost be a duplicate of these Q&A and its accepted answer.
Powershell - Output Color for certain results
Is there a way to specify a font color when using write-output
If you are saying, that you are sending this to a form, then you have to handle color in the form properties code.

Powershell script as a step in sql job giving error

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

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.

Powershell copy file with variable

I'm trying to run the following script that I thought was quite simple. What am I doing wring here...
[Environment]::UserName = $username
Write-Host "The user is $username"
$from = "c:\Users\" + $username + "\favourites\*.*"
$to = "c:\test"
Write-Host "This is from dir: $from"
Write-Host "This is to dir: $to"
Copy-Item $from $to
The script does not seem to like the + $username + ...
I think you got your first line the wrong way around. Currently you're assigning an empty variable (value of it should be $null) to $Env:UserName, thus overwriting the username, not reading it.
I think it should be
$username = [Environment]::Username
or, as noted above, you can access environment variables via the special Env: drive:
$username = $Env:Username
And unrelated to your problem, just a matter of nicer code:
You can put the username directly into the string (which you seem to know, as demonstrated a line above – where you don't need a string in this case, though):
$from = "C:\Users\$username\favourites\*"
You don't need to fetch the user name at all, you can use
$Env:UserProfile
or
[Environment]::GetFolderPath([Environment+SpecialFolder]::UserProfile)
or even
[Environment]::GetFolderPath([Environment+SpecialFolder]::Favorites)
which might ultimately be what you're after, here.

How to search with multiple keys in a hash table in powershell

I'm writing a Powershell script and in it I'm using a hash table to store information about database checks. The table has 5 keys (host, check, last execution time, last rep, status) and I want to search in my table for values where:
$s = $table where $host -eq $hostname -and check -eq $check
Does anyone have any idea how this is done? And if it makes any difference, the script cannot rely on .NET framework higher than 2.0
I´m new to Powershell and scripting in general so this might be very obvious but I still can't seem to find an answer on Google. Also if someone knows a good reference page for Powershell scripting I would really appreciate a link.
Gísli
EDIT: Don't see how it matters but here is a function I use to create a hash table:
function read_saved_state{
$state = #{}
$logpos = #{}
$last_log_rotate = 0
foreach($s in Get-Content $saved_state_file){
$x = $s.split('|')
if($x[0] -eq 'check'){
$state.host = $x[1]
$state.check = $x[2]
$state.lastexec = $x[3]
$state.lastrep = $x[4]
$state.status = $x[5]
}
elseif($x[0] -eq 'lastrotate'){
$last_log_rotate = $x[1]
}
elseif($x[0] -eq 'log'){
$logpos.lastpos = $x[3]
}
}
$saved_state_file has one line for each check run and can also have a line for last log rotate and last log position. There can be as many as 12 checks for one host.
I'm trying to extract a particular check, run at a particular host, and changing the lastexec_time, last_rep and status.
return $state,$logpos,$last_log_rotate
}
Assuming you have an array or list of hashtables (not entirely clear from the question), your syntax is pretty close:
$s = $tables | where {($_.host -eq $hostname) -and ($_.check -eq $check)}