How to pass parameters to SQL script via Powershell on place of -inputfile param -serverinstance param\param -database param - powershell-4.0

invoke-sqlcmd -inputfile "C:\Duke\DBError.sql" -serverinstance "'$svr\$inst'" -database "test"
this is my powershell line of code i want to use param on place of hard code string pls help me is some know the solution

i got solution solution is as below
invoke-sqlcmd -inputfile $path -serverinstance $svr\$inst -database $DB

Related

How to get full name from domain name

So a while back, I managed to make a bat file that would let me enter in somone's username.
Then, it would search the domain for the full name and I could use that for other work. The bat I used would spit out JUST the fullname and put it in a variable.I know I can use the net user /domain $username command, but that doesn't let you single out a result, as far as I'm aware
Unfortunately, I lost it and I can even fine the tutorial I used to help me with it. Does anyone know how this might be done? I did it a few years back on a windows 7 machine, I'm not sure if that changes anything.
Powershell is a much better option for pulling AD info and exporting it. Using the PS AD Module you could do something similar to Get-ADUser -filter $username -properties Name | Select-Object Name From here you could store this info in a variable or write it to a file etc. I will also link to the AD Module documentation for reference on Get-ADUser
If your variable $username is the SamAccountName for the user, just do PowerShell:
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -Properties DisplayName
You now have an object with these user properties: DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName, DisplayName
Only DisplayName needs to be asked for, all other properties are returned by default using Get-ADUser
So if you want just the DisplayName ('FullName' as you call it), just return that:
$fullName = (Get-ADUser -Filter "SamAccountName -eq '$username'" -Properties DisplayName).DisplayName

How to format CCM_UserAffinity output to tyoe Microsoft.PowerShell.Commands.LocalPrincipal

I am trying to create a deployment script which adds freshly deployed workstation primary users to local admin group. I utilized CCM_userAffinity class to obtain username, however - Add-LocalGroupMember does not accept its output.
Ive tried creating task sequence variable to pass into powershell script which adds to group with no success either. Preferably the solution would be integrated within deployment TS, however due to no success i have reverted to ps package deployment.
$computer = "LocalHost"
$namespace = "root\ccm\Policy\Machine"
$query = "ConsoleUser"
$PrimaryUser = Get-WmiObject -class CCM_UserAffinity -computername $computer -namespace $namespace | select-object $query | format-wide
i expected the output from -class CCM_UserAffinity to be accepted by Add-LocalGroupMember, however i get this instead -
Add-LocalGroupMember : Cannot bind parameter 'Member'. Cannot convert the "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" value of type
"Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" to type "Microsoft.PowerShell.Commands.LocalPrincipal".
As you plan on using the value you retrieve and not displaying it there is no need to use something like "format-wide" which only makes the output human readable and is the reason for your FormatStartData datatype.
You can just use :
$PrimaryUser = (Get-WmiObject -class CCM_UserAffinity -computername $computer -namespace $namespace).ConsoleUser
which returns a string and that is taken by the -Member argument of Add-LocalGroupMember
One thing to keep in mind is that in theory there can be more than one ConsoleUser per machine. So the ConsoleUser might be an Array or not. If you can guarantee that there is always only one user in your environment per machine (at the point where the ts runs) you can just use it as is. Otherwise you would have to specify which user you want to use and I can of course not tell you what a good rule for that for your environment would be.
Also I hope you checked that the WMI class CCM_UserAffinity is already populated at the stage where you want to run this script, I could not tell you if this is the case.

Validate parameters for function doesnt work for OU and CN

I am trying to validate my OUs for a function with the following snippet
Param(
[parameter(Mandatory=$True,Position=1)]
[ValidateScript({Get-ADOrganizationalUnit -Identity $_ -Server $Domain})]
[String]$SourceOu
)
This works for normal OUs like the following like a charm
"OU=Desktops,OU=Germany,DC=dom,DC=de")
But I also need to process the built in AD containers like these
"CN=Computers,DC=dom,DC=de",
Unfortunately they fail (maybe because their distinguishedName starts with CN and not with OU like for other OUs) with the error:
Delete-OldADaccount : Cannot validate argument on parameter 'SourceOu'. Cannot find an object with identity: 'CN=Computers,DC=dom,DC=de' under: 'DC=dom,DC=de'.
Is there a way around this or can I just not check both types with one cmdlet? :(
Maybe just check that the object is a container?
Param(
[parameter(Mandatory=$True,Position=1)]
[ValidateScript({"container","organizationalUnit" -contains (Get-ADObject -Identity $_ -Server $Domain).ObjectClass})]
[String]$SourceOu
)
EDIT: Ah. It should be container or organizationalUnit. Updated.

Powershell how to pipe an interactive command

I am connection to a database via an interactive SQL-Command-Line-Utility and when I am executing an SQL command, I want to pipe the output to another power shell cmdlet, for example out-gridview.
Lets say for example I connect to a Sybase ASE database, and I login with
C:\users\user>isql -U<user> -S<SI>
[password]:
1>use master
2>go
1>SELECT * FROM sysusers
2>go | out-gridview
The pipe to out-gridview, nor any other cmdlet, is working. I can redirect the output to a file via > nonetheless, but I think its pre-implemented in the isql-command-line-utility.
Has anyone an idea how to pipe this stuff? I am well aware that there are scripts like this
$query="select * from syslogins"
$conn=New-Object System.Data.Odbc.OdbcConnection
$conn.ConnectionString= "driver={Adaptive Server Enterprise};
dsn=SERVER_NAME;db=master;na=IP,PORT;uid=SOMEUSER;pwd=******;"
$conn.open()
$cmd=new-object System.Data.Odbc.OdbcCommand($query,$conn)
$cmd.CommandTimeout=30
write-host $query
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.odbc.odbcDataAdapter($cmd)
write-host $ds
$da.fill($ds)
$ds.Tables[0] | out-gridview
$conn.close()
But I dont' want to store my password in clear text inside of a script. I want to login to a session, then execute the commands and then pipe my information.
You can't use cmdlets inside a console application. Console applications return text, while cmdlets work with object. You would need to use something like your second sample or run a "script" in isql and parse the text-output to objects.
Since you don't want to automate this you could simply use Read-Host to get the password when running the script.
#Ask for password
$pass = Read-Host Password
$query="select * from syslogins"
$conn=New-Object System.Data.Odbc.OdbcConnection
#User password-variable in string
$conn.ConnectionString= "driver={Adaptive Server Enterprise};
dsn=SERVER_NAME;db=master;na=IP,PORT;uid=SOMEUSER;pwd=$pass;"
$pass = ""
$conn.open()
$cmd=new-object System.Data.Odbc.OdbcCommand($query,$conn)
$cmd.CommandTimeout=30
write-host $query
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.odbc.odbcDataAdapter($cmd)
write-host $ds
$da.fill($ds)
$ds.Tables[0] | out-gridview
$conn.close()
U can replace
go | out-gridview
with
go > out-gridview
In this way, U just redirected the output to out_gridview.

Remote Exchange Powershell session with variables

I have a beginner's knowledge in scripting and programming and have a set of PowerShell commands that I am having issues with figuring out how to turn it into a script.
I can successfully run the following remote commands from my Windows 7 machine by running the Exchange 2007 PowerShell console as my domain administrator account and then running the following commands to pass the commands to the Exchange 2013 hybrid server for use with Office 365:
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://hybridexch2013.contoso.com/PowerShell/ -Authentication Kerberos
Import-PSSession $Session
Enable-RemoteMailbox jame.doe#contoso.com -RemoteRoutingAddress jane.doe#contosoinc.mail.onmicrosoft.com
The more I look into this I don't know that I am making progress. See below for how my logic is working in my head on this. I understand this is incorrect and incomplete. I have commented out a function I had earlier but wasn't sure if I was doing it correct or if it was needed at all.
param($enableMailbox)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://hybridexch2013.contoso.com/PowerShell/ -Authentication Kerberos
Import-PSSession $Session -AllowClobber
$fname = Read-Host "What is the user's first name?"
$lname = Read-Host "What is the user's last name?"
#function Func($enableMailbox)
#{
$enableMailbox = "Enable-RemoteMailbox $fname.$lname#contoso.com -RemoteRoutingAddress $fname.$lname#contosoinc.mail.onmicrosoft.com"
#}
#Func $enableMailbox
Write-Host $enableMailbox
I also find that if I manually run:
Enable-RemoteMailbox $fname.$lname#contoso.com -RemoteRoutingAddress $fname.$lname#contosoinc.mail.onmicrosoft.com
I get nothing. So I am not even understanding how you pass variables to the string to run the command correctly. Even if I run:
$fname = "Jane"
$lname = "Doe"
$enableMailbox = "Enable-RemoteMailbox $fname.$lname#contoso.com -RemoteRoutingAddress $fname.$lname#contosoinc.mail.onmicrosoft.com"
Write-Host $enableMailbox
I get no results.
I was trying to understand the param function using help from these pages: Powershell script with params *and* functions
Passing a variable to a powershell script via command line
https://devcentral.f5.com/blogs/us/powershell-abcs-p-is-for-parameters
http://www.experts-exchange.com/Programming/Languages/Scripting/Powershell/Q_27900846.html
But I am finding the param function difficult to understand and not sure I am even going in the right direction here. So far the only thing that seems to work is connecting to the PowerShell remotely.
Please help if I am am to be helped with this one and lack of my abilities here.
Param Function in short...
Function Write-Something
{
Param($InputText)
Write-Host $InputText
}
Write-Something Hello
Result is: Hello
Use Param Section to add Parameters to your Function like in the example above,
So for your Script:
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://hybridexch2013.contoso.com/PowerShell/ -Authentication Kerberos
Import-PSSession $Session -AllowClobber
Function Enable-MBX
{
Param($Fname,$Lname)
Enable-RemoteMailbox "$Fname $Lname" -RemoteRoutingAddress "$fname.$lname#contoso.mail.onmicrosoft.com"
}
Enable-MBX Jane Doe
I think you're just confused about Write-Host.
I'm not certain if you're trying to write the enable-remotemailbox to console or execute it. The code you have should work fine for writing to console (screen) but won't execute the command. To execute the command:
Enable-RemoteMailbox "$fname.$lname#contoso.com" -RemoteRoutingAddress "$fname.$lname#contosoinc.mail.onmicrosoft.com"
Anything inside of double-quotes will expand. Ex: "$fname" will expand to "Bob" if $fname is equal to "Bob". If you encapsulate the whole command in quotes in a variable though, the Write-Host will NOT execute the command. Write-Host is designed to write output to the screen so you'll just see the command in the console.
If you want to further expand, you can use the sub-string operator $(). Ex:
Write-Host "$($fname.length).$($lname.length)"
Comes back as "3.5" for "Bob" and "Smith".
To avoid expansion, use single quotes:
Write-Host '$($fname.length).$($lname.length)'
Writes "$($fname.length).$($lname.length)" to the console.
The following (similar to your code) without quotes: Write-Host $fname.$lname#contoso.com will try to pull the $lname#contoso.com Property of $fname which in this context doesn't make sense (doesn't exist). To elaborate, it would be equivalent to Write-Host $fname.($lname#contoso.com).

Resources