Powershell Get-PrinterPort Invalid Query - arrays

Having trouble with this function something with the Get-PrinterPort erroring out.
Error Message(s) below
Get-PrinterPort : Invalid query
At line:10 char:16
+ $printer = Get-PrinterPort -Name $test | ft DeviceURL | out-strin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (MSFT_PrinterPort:ROOT/StandardCimv2/MSFT_PrinterPort) [Get-PrinterPort], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041017,Get-PrinterPort`
Exception calling "Substring" with "2" argument(s): "Length cannot be less than zero.
Parameter name: length"
At line:16 char:5
+ $printhostname = $printer.Substring(0, $pos)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException`
This is the code, I've narrowed it down to a suspected issue with the Get-PrinterPort -Name part, the guides say it takes a string[] but doesn't like the output from out-string. Any tips or blinding errors?
function Get-HostNameFromPrinterName {
$servername = Read-Host -Prompt "Enter the name of the Printer"
$WSD = (Get-WmiObject -class Win32_Printer | where Name -match $servername | select PortName) | out-string
$pos = $WSD.IndexOf("W")
$WSD = $WSD.Substring($pos)
$pos = $WSD.IndexOf("`n")
$WSD = $WSD.Substring(0, $pos)
$printer = Get-PrinterPort -Name $WSD | ft DeviceURL | out-string
$pos = $printer.IndexOf("/")
$printer = $printer.Substring($pos+1)
$pos = $printer.IndexOf("/")
$printer = $printer.Substring($pos+1)
$pos = $printer.IndexOf("/")
$printhostname = $printer.Substring(0, $pos)
write-host $printhostname
}
Also please forgive any formatting errors :p
EDIT: After testing the variable type returns system.string
This program does the same thing however it works fine.
function Get-HostNameFromWSD {
$WSD = Read-Host -Prompt 'Input WSD'
$printer = Get-PrinterPort -name $WSD | ft DeviceURL | out-string
$pos = $printer.IndexOf("/")
$printer = $printer.Substring($pos+1)
$pos = $printer.IndexOf("/")
$printer = $printer.Substring($pos+1)
$pos = $printer.IndexOf("/")
$printhostname = $printer.Substring(0, $pos)
write-host $printhostname
}
This variable also returns system.string. Not sure where the error lies.

Asked the same question over on Technet, this answer worked for me.
Get-WmiObject Win32_Printer |?{$_.portname -match '^WSD'}|select PortName,SystemName

Related

Powershell ListView.ItemsSource type error

I'm struggling with sending variables from one file to another.
Here's function from my main file:
Function Set-ManagerWindowForms ($Manager){
$WPFManager.Text = $Manager.DisplayName
$accounts = .\Scripts\Helpers\FindUserAlike.ps1 -FirstName_Param $Manager.GivenName -LastName_Param $Manager.Surname -Domain_Param "domain.com"
$WPFAccountListView.ItemsSource = $accounts
}
And the helping function I'm calling looks like this:
param(
[Parameter(Mandatory = $true)][String]$FirstName_Param,
[Parameter(Mandatory = $true)][String]$LastName_Param,
[Parameter(Mandatory = $true)][String]$Domain_Param
)
$accounts = Get-ADUser -Filter {GivenName -like $FirstName_Param -and Surname -like $LastName_Param} -Server $Domain_Param
$itemSource = #()
ForEach ($account in ($accounts | Sort-Object SamAccountName)) {
$itemSource += [PSCustomObject]#{
samAccountName = $account.SamAccountName
firstName = $account.GivenName
lastName = $account.Surname
}
}
return $itemSource
Now - when I try to send $accounts to .ItemsSource I'm getting an error message:
Exception setting "ItemsSource": "Cannot convert the "#{samAccountName=id; firstName=name; lastName=surname}" value of type "System.Management.Automation.PSCustomObject" to type "System.Collections.IEnumerable"."
+ $WPFAccountListView.ItemsSource = $accounts
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Code is working perfectly fine if I place it in the "main" script.
Can't really understand what's happening, I even tried to set $accounts to IEnumerable type, but it actually gave me even more errors.
Any advice, tip will be greatly appreciated.

Powershell SQL Server stored procedure backup

I am trying to backup one particular stored procedure from a SQL Server database by passing parameters from a Python program. Here is the code that I have tried but I keep getting an error.
param([string]$server='dbsed0898', [string]$dbname='global_hub',[string]$sp='dbo.gs_eligibility')
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SMO”) | out-null
$SMOserver = 'Microsoft.SqlServer.Management.Smo' #-argumentlist $server
$srv = New-Object("$SMOserver.Server") $server
$db = $srv.databases[$dbname]
$Objects = $db.storedprocedures[$sp]
$scripter = new-object ("$SMOserver.Scripter") $srv
$Scripter.Script($Objects) | Out-File
" C:\Users\fthoma15\Documents\backup_03212020.sql"
$db = $SMOserver.databases[$dbname]
$Objects = $db.storedprocedures[$sp]
$Scripter.Script($Objects) | Out-File
"C:\Users\fthoma15\Documents\backup_03212020.sql"
Error:
Multiple ambiguous overloads found for "Script" and the argument count: "1".
At line:12 char:5
+ $Scripter.Script($Objects) | Out-File "C:\Users\fthoma15\Document ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Can someone help me?
Here is what i did.
param([string]$server='test', [string]$dbname='test',[string[]]$sp=('test','test'))
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SMO”) | out-
null
$SMOserver = new-object ("Microsoft.SqlServer.Management.Smo.Scripter") #-argumentlist
$server
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("$server")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $srv.Databases.Item("$dbname")
$Objects = $db.storedprocedures[$sp[1,3]]
$scripter = new-object ("$SMOserver") $srv
$Scripter.Script($Objects) | Out-File
"C:\Users\fthoma15\Documents\backup_03212020.sql"
As suggested by AlwaysLearning, i changed the sp variable to an array list,splitting both schema and sp name.

Issue with Powershell SMO SQL Server restore

I am running into an issue with doing a Powershell SQL restore. I have this code
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
$backupFile = 'C:\Temp\User_20191029152532.bak'
$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "(local)"
$backupDevice = New-Object("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") ($backupFile, "File")
$smoRestore = new-object("Microsoft.SqlServer.Management.Smo.Restore")
$smoRestore.NoRecovery = $false;
$smoRestore.ReplaceDatabase = $true;
$smoRestore.Action = "Database"
$smoRestorePercentCompleteNotification = 10;
$smoRestore.Devices.Add($backupDevice)
$smoRestoreDetails = $smoRestore.ReadBackupHeader($server)
"Database Name from Backup Header : " +$smoRestoreDetails.Rows[0]["DatabaseName"]
$smoRestore.Database =$smoRestoreDetails.Rows[0]["DatabaseName"]
$smoRestoreFile = New-Object("Microsoft.SqlServer.Management.Smo.RelocateFile")
$smoRestoreLog = New-Object("Microsoft.SqlServer.Management.Smo.RelocateFile")
$smoRestoreFile.LogicalFileName = $smoRestoreDetails.Rows[0]["DatabaseName"]
$smoRestoreFile.PhysicalFileName = $server.Information.MasterDBPath + "\" + $smoRestore.Database + "_Data.mdf"
$smoRestoreLog.LogicalFileName = $smoRestoreDetails.Rows[0]["DatabaseName"] + "_Log"
$smoRestoreLog.PhysicalFileName = $server.Information.MasterDBLogPath + "\" + $smoRestore.Database + "_Log.ldf"
$smoRestore.RelocateFiles.Add($smoRestoreFile)
$smoRestore.RelocateFiles.Add($smoRestoreLog)
$smoRestore.SqlRestore($server)
Everything works fine if I run this. However, I would like to provide a variable for which backup to restore. So I changed the top part of the code to this:
$path = 'C:\Temp'
$db_name = 'User'
$file = Get-ChildItem $path '*.bak' | Select-Object basename | Where-Object {$_.basename -like $db_name + '*' }
$backupFile = $path + '\' + $file
When I make this change, I start getting the below error.
Exception calling "ReadBackupHeader" with "1" argument(s): "An exception occurred while executing a Transact-SQL statement or batch."
At line:23 char:1
+ $smoRestoreDetails = $smoRestore.ReadBackupHeader($server)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ExecutionFailureException
Not really sure why it will not accept the $file variable that I am passing. If I look at the variable, it is returning the right value.
Stupid issue on my part. $file did not include the extension. Adding the .bak to $file fixed the issue.

Powershell Script Issue with SQL Server 2012/2014

I have a PowerShell script which works well when I run it on server with SQL Server default instance (MSSQLSERVER) but the same script fails on a server with a named instance (MSSQL$instance)
For the default instance (MSSQLSERVER)
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$service = Get-service -name 'MSSQLSERVER'
$status = $service.status
$CreateDB = "db-Test"
if ( $status -eq "Running" )
{
'Success' | Out-File -FilePath c:\sqltest.log -Encoding ASCII
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, "$CreateDB")
$db.Create()
$db.CreateDate
}
else
{
'Failed' | Out-File -FilePath c:\sqltest.log -Encoding ASCII
}
Above script works very well. But below script throws error :
For named instance :
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$service = Get-service -name 'MSSQL$instancename'
$status = $service.status
$CreateDB = "db-Test"
if ( $status -eq "Running" )
{
'Success' | Out-File -FilePath c:\sqltest.log -Encoding ASCII
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, "$CreateDB")
$db.Create()
$db.CreateDate
}
else
{
'Failed' | Out-File -FilePath c:\sqltest.log -Encoding ASCII
}
Above script for named SQL instance throws below error :
New-Object : Exception calling ".ctor" with "2" argument(s): "SetParent failed for Database 'Netmagic-Test'. "
At C:\mssql-test.ps1:11 char:7
+ $db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, "$CreateDB")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\mssql-test.ps1:12 char:1
+ $db.Create()
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Error Screen
Thanks,
Viral

Powershell - Unable to Compare Strings Output from Sharepoint List

After extracting a list from SharePoint, I need to validate each Item against its BRTeam value. Here is the script:
cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
$sourceWebUrl = "http://theoracle/WorkingHere/"
$sourceListName = "Policies & Procedures"
$spSourceWeb = Get-SPWeb $sourceWebUrl
$spSourceList = $spSourceWeb.Lists[$sourceListName]
$spSourceItems = $spSourceList.Items
$spSourceItems | ForEach-Object {
Write-Host $_['Name']
Write-Host $_['BRTeam']
}
The code works fine in terms of getting the data and writing the required items to the host.
However, if I add the following If-Statement to validate the items, I am seeing an error:
if ($_['BRTeam'].Contains('HR')) {
Write-Host $_['Name']
Write-Host $_['BRTeam']
}
I have also tried replacing the Boolean check with $x -contains 'HR' after assigning $x = $_['BRTeam'], but this returns no output (no error either). Error below:
Method invocation failed because [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue] doesn't contain a method named 'Contains'.
At line:21 char:9
+ if ($_['BRTeam'].Contains('HR')) {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Can anyone let me know what I am missing here?
I was able to resolve this by using the -Match operator instead:
$spSourceItems | ForEach-Object {
#Write-Host $_['ID']
#Write-Host $_['Workflow Started']
$x = $_['BRTeam']
if ($_['BRTeam'] -Match 'HR') {
Write-Host $_['Name']
}
}
If I am concerned that some other BRTeams may contain HR without actually being HR, I could also perform a -NotMatch against all the other departments.
E.g.:
$spSourceItems | ForEach-Object {
#Write-Host $_['ID']
#Write-Host $_['Workflow Started']
$x = $_['BRTeam']
if ($_['BRTeam'] -Notmatch 'Accounts' -And $_['BRTeam'] -Notmatch 'IT') {
Write-Host $_['Name']
}
}

Resources