why powercli script is not accepting the variable parameters during the execution? - powercli

When I am trying to run this powercli script getting below error
The argument is null or empty. Provide an argument that is not null or empty, and then try the | command again
but its is working with static value. any clue why this is happening. here is the command with parameters
/usr/bin/pwsh /ansible-vmware/vmwarehost-config-playbooks/lag-add-host.ps1 -vcenter_fqdn "10.10.0.1" -vcenter_username "xxxxxx.abc.com" -vcenter_password "XXXX" -newhostname "hostdone1" -domainname "abc.com" -dvswitchname_1 "dv1" -nic1_pnicmac1 "ac:1f:6b:cb:83:3a" -cluster_name "xyzclr" -lag_name1 "lag1-0"
Script content:
#!/usr/bin/pwsh -command
param(
[String] $vcenter_fqdn,
[String] $vcenter_username,
[String] $vcenter_password,
[String] $newhostname,
[String] $domainname,
[String] $dvswitchname_1,
[String] $cluster_name,
[String] $lag_name1,
[String] $nic1_pnicmac1
)
# VC connectivity
Write-Host "Connecting to VC host " $vcenter_fqdn
Connect-VIServer -Server $vcenter_fqdn -User $vcenter_username -Password $vcenter_password -Force
$esxName1 = Get-cluster -Name $cluster_name | Get-VMhost -Name $newhostname.$domainname
$esxName=$esxName1.name
$vdsName1 = Get-VDSwitch $dvswitchname_1
$vdsName = $vdsName1.name
Add-VDSwitchVMHost -VMHost $esxName -VDSwitch $vdsName1
$esxihostnic1 = Get-VMHost hostdone1.examlab.com | Get-VMHostNetworkAdapter -Physical | Where-Object {$_.Mac -eq "$nic1_pnicmac1"}
$pnicName = $esxihostnic1.name
$uplinkName = $lag_name1

#!/usr/bin/pwsh -command
param(
[String] $vcenter_fqdn,
[String] $vcenter_username,
[String] $vcenter_password,
[String] $newhostname,
[String] $domainname,
[String] $dvswitchname_1,
[String] $cluster_name,
[String] $lag_name1,
[String] $nic1_pnicmac1
)
# VC connectivity
Write-Host "Connecting to VC host " $vcenter_fqdn
Connect-VIServer -Server $vcenter_fqdn -User $vcenter_username -Password $vcenter_password -Force
$esxName1 = Get-cluster -Name $cluster_name | Get-VMhost -Name $newhostname.$domainname
$esxName=$esxName1.name
$vdsName1 = Get-VDSwitch "$dvswitchname_1"
$vdsName = $vdsName1.name
Add-VDSwitchVMHost -VMHost $esxName -VDSwitch $vdsName1
$esxihostnic1 = Get-VMHost hostdone1.examlab.com | Get-VMHostNetworkAdapter -Physical | Where-Object {$_.Mac -eq "$nic1_pnicmac1"}
$pnicName = $esxihostnic1.name
$uplinkName = $lag_name1

Related

powershell not exporting

hi i am running the following query in powershell:
Import-Module Hall.psm1
$Database = 'Report'
$Server = '192.168.1.2'
$Query = 'SELECT all * FROM [Report].[dbo].[TestView]'
$LogLocation = "\\Report\LogFile.csv"
$DynamicYear = (Get-Date).Year
$DynamicMonth = (Get-Culture).DateTimeFormat.GetMonthName((Get-Date).Month)
$FileDestination = "\\Report\MONTHLY REPORTS\"+$DynamicYear+"\"+$DynamicMonth+"\"
$Outputfilename='TestView-'+(Get-Date).ToString('MM-dd-yyyy')+'.csv'
$LocalCreate = 'C:\Scripts\LocalCreate\'
$FolderPathExtension = "Microsoft.PowerShell.Core\FileSystem::"
$CodeDestination = $FolderPathExtension+$FileDestination
$filedest=$LocalCreate+$outputfilename
$Logfile = $FolderPathExtension+$LogLocation
Invoke-sqlcmd -querytimeout 120 -query "
$Query
" -database $database -serverinstance $server |
ConvertTo-Csv -NoTypeInformation | # Convert to CSV string data without the type metadata
Select-Object -Skip 0 | # Trim header row, leaving only data columns
% {$_ -replace '"',''} | # Remove all quote marks
Set-Content -Path $filedest
(gc $filedest) | ? {$_.trim() -ne "" } | set-content $filedest
if(Test-Path ($filedest)) {
Move-Item -Path $filedest -Destination $CodeDestination -Force
$LogType = 'INFO'
$LogEntry = "$filedest MovedTo $To"
Write-Log -Message $LogEntry -Level $LogType -Logfile $Logfile
}
which works fine without any issue if the query has data.
however, if the query does not have any data it does not create a .csv. how can i get it to create a blank .csv? or .csv with headers only?
Use New-Item -ItemType File -Path $filedest before your Invoke-SqlCmd Or ConvertTo-Csv

Get the SQL Versions of all servers with get-wmiobject

I would like to get all the installed version values of SQL on over 200 different Servers.
The plan is, to have all the Server Names in the ServerListSQLVersions.txt
and to get all the SQL Versions into the CSV.
$Username = ''
$Password = ''
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$SecureString = $pass
# Users you password securly
$MySecureCreds = New-Object -TypeName
System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString
$Array = #()
##Create a Folder called SQLVersions##
$scriptPath = "C:\Transfer to SV000229\SQL Script"
$server = Get-Content "$scriptPath\ServerListSQLVersions.txt"
$wmiobj = Get-WmiObject -class Win32_product | where Name -like '*SQL*' | Select-Object name,version
function getWMIObject($server, $wmiobj, $MySecureCreds) {
$result = Get-WmiObject $wmiobj -ComputerName $server -Credential $MySecureCreds
#Write-Host "Result: "$result
$Array+= $Result
}
$Array = Export-Csv $scriptpath\output.csv -NoTypeInformation
My output in the CSV is:
Length
0
I used a
foreach($computer in $computers){
instead of the function and gave the information manually.
Also the output was not abled to Export, because i used an = instead of an |
Works now.

Get variable from tenant in Octopus

Is there any way to get a variable from tenant in Octopus server?
I already extracting variable from projects, using code below, but this method is not working for tenants:
Import-Module "C:\Program Files\WindowsPowerShell\Modules\Octopus-Cmdlets\0.4.4\Octopus-Cmdlets.psd1"
connect-octoserver http://octohost.cloudapp.azure.com:8082 API-12345678901234567890
$raw = (Get-OctoVariable someproject somevariable | Where-Object { $_.Environment -eq "DEV" } )
$jsonfile = "c:\dataapi.json"
$raw.Value | ConvertFrom-Json | ConvertTo-Json | Out-File $jsonfile -Encoding UTF8
$data = Get-Content $jsonfile -Encoding UTF8 | ConvertFrom-Json
$data | ConvertTo-Json | Set-Content $jsonfile -Encoding UTF8
There is at least the following way to get a variable from a tenant in Octopus Deploy. I got this working with making OctopusClient.dll calls.
Add-Type -Path $OctopusClientDll #this should point to the dll
$Endpoint = New-Object Octopus.Client.OctopusServerEndpoint $octopusURI, $apiKey
$Repository = New-Object Octopus.Client.OctopusRepository $Endpoint
$TenantEditor = $Repository.Tenants.CreateOrModify($TenantName)
$Vars = $TenantEditor.Variables.Instance.LibraryVariables
$VarSet = $Vars[$COMMON_TENANT_VARSET_ID] # you need to know this
$VarTemplate = $VarSet.Templates | Where-Object -Property Name -eq "Tenant.VariableName"
$VariableValue = $VarSet.Variables[$varTemplate.Id].Value

tst10 telnet scripting continuously

I am using this website (http://npr.me.uk/scripting.html) to connect to telnet and run command. It returns me some information. I need to get this info every 4 seconds. How do I do that? Now it runs but reconnects everytime, so I have to wait while it opens a connection and it takes much more than 4s. Bat file:
echo off
cls
if exist r1.txt del r1.txt
if exist r2.txt del r2.txt
tst10.exe /r:stats.txt /o:r1.txt /m
for /f "skip=30 tokens=*" %%A in (r1.txt) do echo %%A >> r2.txt
del r1.txt
start r2.txt
And stats file:
192.168.xxx.xxx
WAIT "login:"
SEND "myuser\m"
WAIT "Password:"
SEND "mypass\m"
WAIT ">"
SEND "mycommand\m"
WAIT ">"
Use Powershell to program using a csv file with the connections, I am using it for re-programming mfd's
I have a file mfd.txt and a script that reads it in.
I have a telnet script template to change the settings on the mfd and the powershell script creates custom scripts for each mfd and sets dns and hostname parameters. When run, a logfile is piped into a directory for checking later
Script is as follows:
#Process for updating devices quickly using telnet
#Check file exists
c:
cd 'C:\Resources\Telnet'
cls
$fileisthere = $false
$fileisthere = test-path 'C:\Resources\Telnet\mfds.csv'
if ($fileisthere -ne $true)
{
""
Write-Host ("There is no MFD import list C:\Resources\telnet\mfds.csv") | out-file -filepath $logfile -force
""
exit
}
Write-Host ("MFD import List is present")
# for each device in devices:
$mfds = import-csv 'C:\Resources\Telnet\mfds.csv'
foreach ($mfd in $mfds)
{
# ping device and check for response
$mfdname = $mfd.name
$mfdip = $mfd.ipaddress
$mfddns1 = $mfd.dns1
$mfddns2 = $mfd.dns2
$mfdhostname = $mfd.serial
""
Write-Host ("Updating device $($mfdname) on IP address $($Mfdip) ")
""
("Updating device $($mfdname) on IP address $($Mfdip) ") | out-file -filepath $logfile -Append -force
if(!(Test-Connection -Cn $mfdip -BufferSize 16 -Count 1 -ea 0 -quiet))
{
Write-Host ""
Write-Host ("MFD $($mfdname) is offline or not at this address")
Write-Host ""
"" | out-file $logfile -Append -force
("MFD $($mfdname) is offline or not at this address") | out-file $logfile -Append -force
"" | out-file $logfile -Append -force
}
else
{
#find replace script
# Device is present and add to script header
$tststring = "$($mfdip) 23"
$tstfile = "$($mfdname)-$($mfdip).txt"
$tstlogfile = "$($mfdname)-$($mfdip).log"
$tststring | out-file $tstfile -force
type dns.txt >> $tstfile
$location1 = "C:\Resources\telnet\$($tstfile)"
$change1 = get-content $location1
$change1 | ForEach-Object { $_ -replace "dns 1 server", "dns 1 server $($mfddns1)"} | Set-Content $location
$location2 = "C:\Resources\telnet\$($tstfile)"
$change2 = get-content $location2
$change2 | ForEach-Object { $_ -replace "dns 2 server", "dns 2 server $($mfddns2)"} | Set-Content $location
$location3 = "C:\Resources\telnet\$($tstfile)"
$change3 = get-content $location3
$change3 | ForEach-Object { $_ -replace "hostname ether name", "hostname ether name $($mfdhostname)"} | Set-Content $location
$location4 = "C:\Resources\telnet\$($tstfile)"
$change4 = get-content $location4
$change4 | ForEach-Object { $_ -replace "devicename name", "devicename name $($mfdhostname)"} | Set-Content $location
# Create variables for update
Write-Host ("Updating $($Mfdname) on IP Address $($mfdIP) ")
$parameter1 = "/r:$($tstfile)"
$parameter2 = "/o:$($tstlogfile)"
#& cmd tst10 $parameter1 $paremeter2
write-host ("$($tstfile) $($tstlogfile)")
new-item $tstfolder -Type directory
move-item $tstfile $tstfolder
move-item $tstlogfile $tstfolder -ErrorAction SilentlyContinue
}
}

How do I check for the SQL Server Version using Powershell?

What's the easiest way to check for the SQL Server Edition and Version using powershell?
Just an option using the registry, I have found it can be quicker on some of my systems:
$inst = (get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
foreach ($i in $inst)
{
$p = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL').$i
(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$p\Setup").Edition
(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$p\Setup").Version
}
Invoke-Sqlcmd -Query "SELECT ##VERSION;" -QueryTimeout 3
http://msdn.microsoft.com/en-us/library/cc281847.aspx
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" "."
$srv.Version
$srv.EngineEdition
Obviously, replace "." with the name of your instance. If you want to see all the methods available, go here.
Hacked up advice from this thread (and some others), this went in my psprofile:
Function Get-SQLSvrVer {
<#
.SYNOPSIS
Checks remote registry for SQL Server Edition and Version.
.DESCRIPTION
Checks remote registry for SQL Server Edition and Version.
.PARAMETER ComputerName
The remote computer your boss is asking about.
.EXAMPLE
PS C:\> Get-SQLSvrVer -ComputerName mymssqlsvr
.EXAMPLE
PS C:\> $list = cat .\sqlsvrs.txt
PS C:\> $list | % { Get-SQLSvrVer $_ | select ServerName,Edition }
.INPUTS
System.String,System.Int32
.OUTPUTS
System.Management.Automation.PSCustomObject
.NOTES
Only sissies need notes...
.LINK
about_functions_advanced
#>
[CmdletBinding()]
param(
# a computer name
[Parameter(Position=0, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ComputerName
)
# Test to see if the remote is up
if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
# create an empty psobject (hashtable)
$SqlVer = New-Object PSObject
# add the remote server name to the psobj
$SqlVer | Add-Member -MemberType NoteProperty -Name ServerName -Value $ComputerName
# set key path for reg data
$key = "SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"
# i have no idea what this does, honestly, i stole it...
$type = [Microsoft.Win32.RegistryHive]::LocalMachine
# set up a .net call, uses the .net thingy above as a reference, could have just put
# 'LocalMachine' here instead of the $type var (but this looks fancier :D )
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName)
# make the call
$SqlKey = $regKey.OpenSubKey($key)
# parse each value in the reg_multi InstalledInstances
Foreach($instance in $SqlKey.GetValueNames()){
$instName = $SqlKey.GetValue("$instance") # read the instance name
$instKey = $regKey.OpenSubkey("SOFTWARE\Microsoft\Microsoft SQL Server\$instName\Setup") # sub in instance name
# add stuff to the psobj
$SqlVer | Add-Member -MemberType NoteProperty -Name Edition -Value $instKey.GetValue("Edition") -Force # read Ed value
$SqlVer | Add-Member -MemberType NoteProperty -Name Version -Value $instKey.GetValue("Version") -Force # read Ver value
# return an object, useful for many things
$SqlVer
}
} else { Write-Host "Server $ComputerName unavailable..." } # if the connection test fails
}
To add to Brendan's code.. this fails if your machine is 64-bit, so you need to test appropriately.
Function Get-SQLSvrVer {
<#
.SYNOPSIS
Checks remote registry for SQL Server Edition and Version.
.DESCRIPTION
Checks remote registry for SQL Server Edition and Version.
.PARAMETER ComputerName
The remote computer your boss is asking about.
.EXAMPLE
PS C:\> Get-SQLSvrVer -ComputerName mymssqlsvr
.EXAMPLE
PS C:\> $list = cat .\sqlsvrs.txt
PS C:\> $list | % { Get-SQLSvrVer $_ | select ServerName,Edition }
.INPUTS
System.String,System.Int32
.OUTPUTS
System.Management.Automation.PSCustomObject
.NOTES
Only sissies need notes...
.LINK
about_functions_advanced
#>
[CmdletBinding()]
param(
# a computer name
[Parameter(Position=0, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ComputerName
)
# Test to see if the remote is up
if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
$SqlVer = New-Object PSObject
$SqlVer | Add-Member -MemberType NoteProperty -Name ServerName -Value $ComputerName
$base = "SOFTWARE\"
$key = "$($base)\Microsoft\Microsoft SQL Server\Instance Names\SQL"
$type = [Microsoft.Win32.RegistryHive]::LocalMachine
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName)
$SqlKey = $regKey.OpenSubKey($key)
try {
$SQLKey.GetValueNames()
} catch { # if this failed, it's wrong node
$base = "SOFTWARE\WOW6432Node\"
$key = "$($base)\Microsoft\Microsoft SQL Server\Instance Names\SQL"
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName)
$SqlKey = $regKey.OpenSubKey($key)
}
# parse each value in the reg_multi InstalledInstances
Foreach($instance in $SqlKey.GetValueNames()){
$instName = $SqlKey.GetValue("$instance") # read the instance name
$instKey = $regKey.OpenSubkey("$($base)\Microsoft\Microsoft SQL Server\$instName\Setup") # sub in instance name
# add stuff to the psobj
$SqlVer | Add-Member -MemberType NoteProperty -Name Edition -Value $instKey.GetValue("Edition") -Force # read Ed value
$SqlVer | Add-Member -MemberType NoteProperty -Name Version -Value $instKey.GetValue("Version") -Force # read Ver value
# return an object, useful for many things
$SqlVer
}
} else { Write-Host "Server $ComputerName unavailable..." } # if the connection test fails
}
Try this
Invoke-SqlCmd -query "select ##version" -ServerInstance "localhost"
Check all available method to Get the build number of the latest Cumulative Update / Service Pack that has been installed in SQL Server
Here is a version I cobbled together from some sources here and there*.
This version does not hit the registry, does not hit SQL, and doesn't even require that the instance be running. It does require that you know the instance name. If you don't know the instance name, you should be able to trivially work it out from this code.
To get this to work, replace "YourInstanceNameHere" with the name of your instance. Don't touch the $ if you do it won't work.
$ErrorActionPreference = "Stop"
$instanceName = "MSSQL`$YourInstanceNameHere"
$sqlService = Get-Service -Name $instanceName
$WMISQLservices = Get-WmiObject -Class Win32_Product -Filter "Name LIKE 'SQL Server % Database Engine Services'" | Select-Object -Property Name,Vendor,Version,Caption | Get-Unique
foreach ($sqlService in $WMISQLservices)
{
$SQLVersion = $sqlService.Version
$SQLVersionNow = $SQLVersion.Split("{.}")
$SQLvNow = $SQLVersionNow[0]
$thisInstance = Get-WmiObject -Namespace "root\Microsoft\SqlServer\ComputerManagement$SQLvNow" -Class SqlServiceAdvancedProperty | Where-Object {$_.ServiceName -like "*$instanceName*"} | Where-Object {$_.PropertyName -like "VERSION"}
}
$sqlServerInstanceVersion = $thisInstance.PropertyStrValue
if ($sqlServerInstanceVersion)
{
$majorVersion = $thisInstance.PropertyStrValue.Split(".")[0]
$versionFormatted = "MSSQL$($majorVersion)"
}
else
{
throw "ERROR: An error occured while attempting to find the SQL Server version for instance '$($instanceName)'."
}
$versionFormatted
*I also received help from and help from this this friend of mine https://stackoverflow.com/users/1518277/mqutub and I didn't want it to go uncredited.
All you need is to connect to SQL Server and run this query:
select ##version
This, of course, will work for any client tool.
Additionally, this is also available:
SELECT SERVERPROPERTY('productversion'),
SERVERPROPERTY ('productlevel'),
SERVERPROPERTY ('edition')
More ways to determine the SQL Server version here: http://support.microsoft.com/kb/321185
Just an expansion of Ben Thul's answer, It loops through a list of all my DB Servers and prints out the current version of the database engine:
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
$computers = #(‘XXXX-OMG-DB-01’,’XXXX-PRO-DB-01’,’XXXX-PRO-DB-02’,
’XXXX-QAT-DB-01', 'XXXX-TST-DB-01’,'YYYY-PRO-DB-01',
'YYYY-PRO-DB-02','YYYY-QAT-DB-01','YYYY-QAT-DB-02',
'YYYY-TST-DB-01','ZZZZ-DEV-DB-01','ZZZZ-DEV-DB-02')
$computers | % {
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $_
if ($null -eq $srv.ComputerNamePhysicalNetBIOS) {
$s = $_.tostring() + ' is unavailable'
$s.tostring()
} else {
$srv.ComputerNamePhysicalNetBIOS + ' ' +
$srv.VersionString + ' ' +
$srv.DatabaseEngineEdition
}
}
Well, here's the old school way, that's easy:
sqlcmd -Q "select ##version;"
And here's how I use it from Serverspec:
require 'windows_spec_helper'
describe 'MS SQL Server Express' do
describe service('MSSQLSERVER') do
it { should be_enabled }
it { should be_running }
end
describe port(1433) do
it { should be_listening }
end
describe command('sqlcmd -Q "select ##version;"') do
its(:stdout) { should match /Microsoft SQL Server 2008 R2 (SP2) - 10.50.4000.0 (X64)/ }
end
end