-Credential parameter not working with Invoke-ASCmd - sql-server

I'm using SqlServer module for powershell( https://www.powershellgallery.com/packages/SqlServer/21.1.18256) and I'm trying to use Invoke-ASCmd with -Credential parameter. The problem is, -Credential parameter is ignored and the current user for whom the powershell is started is used. When I start powershell with the user I want to use for -credential, it works fine.
Official docs say(https://learn.microsoft.com/en-us/powershell/module/sqlserver/invoke-ascmd?view=sqlserver-ps):
"
-Credential
If this parameter is specified, the user name and password passed will be used to connect to specified Analysis Server instance. If no credentials are specified default windows account of the user who is running the tool will be used."
But it does not work that way.
$pwd=ConvertTo-SecureString "something" -AsPlainText -Force
$mycred = New-Object System.Management.Automation.PSCredential("someusername",$pwd)
Invoke-ASCmd -Server "someServer.somewhere" -Credential $mycred -InputFile "C:\path\to\xmla\1.xmla"
Any ideas on how to fix this?

looks like you are using an old version of PowerShell. Try 5.1

Related

Xp_CmdShell Powershell Script No Valid Module Found

I'm trying to run a PS1 file in T-SQL using XP_CMDSHELL, like so:
exec xp_cmdshell 'powershell -ExecutionPolicy bypass -command "C:\Users\sleven\Documents\DimAcctImport.ps1"'
The powershell script is as follows:
import-module dbatools
Import-DbaCsv -SqlInstance 'MSSQL' -Database 'Test' -Table 'Account' -Path "R:\Data\Account.csv" -Delimiter ',' -Quote '"' -KeepNulls -NoProgress
This script uses the cmdlet Import-DbaCSV of module DbaTools to import the CSV to the target table.
Here is the error I receive in SSMS:
import-module : The specified module 'dbatools' was not loaded because no valid module file was found in any module
directory.
At C:\Users\sleven\Documents\DimAcctImport.ps1:1 char:1
+ import-module dbatools
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (dbatools:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
The module is installed and runs as expected if I copy the PowerShell script and run it in PS ISE.
I'm using SQL Developer Edition on the same PC as I'm using to run the sp - my local PC.
What am I missing?
EDIT: Adding output from get-module and $PSVersionTable
PS> (Get-Module -ListAvailable dbatools).Path:
C:\Users\sleven\Documents\WindowsPowerShell\Modules\dbatools\0.9.834\dbatools.psd1
PS> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.18362.145
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.18362.145
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Using Import-Module cmdlet tells PowerShell to look for cmdlet only in certain folders. You can check these folders by checking environment variable PSModulePath (splitting added for better visibility):
$env:PSModulePath -split ';'
In that case, when running PowerShell by xp_cmdshell, that folder is not included in PSModulePath (might happen as well if you use different account as your module is currently in your profile folder). Now you have two options:
Reference the module using its path, not name. You can get path using (get-module -ListAvailable dbatools).path:
# Replace the path with the path you found with Get-Module
Import-Module 'C:\path\to\module\dbatools.psd1
Modify your $env:PSModulePath. As that topic is more broader, let me give you the link to the docs. Remember that you should set that variable for the user running xp_cmdshell. As RThomas mentioned, by default it's not your user account. See linked answer for explanation on that topic.
NOTE (credits go to #David Browne - Microsoft from his comments):
If you're going to set the environment variable, it should be a system environment variable, as you wouldn't want this process to break if you change the SQL Server service account. And remember, setting a system environment variable requires a reboot for services to see the change.
It's likely an account issue. Keep in mind that running xp_cmdshell by default runs everything as the service account behind the SQL Server instance. So you'll want to verify what account this is.
If it's a built in system account this can cause strange behavior when it comes to rights.
If it's a windows or a domain account then you'll want to test externally to SQL Server by running the PS file not as yourself but as the same account SQL Server uses as a service account. You can do this easily by opening the cmd shell with shift/right click and specifying the other account.
Your other option is to set up a proxy account for the xp_cmdshell call to use. Instructions on how to do this can be found in Microsoft documentation.

Can you import .CSV data into SQL Server using commands from Powershell 3 or 4?

Is there a Powershell script for PowerShell version 3 or version 4 that allows you to import values from a .CSV file into a SQL table?
I'm trying to figure out whether I can script a PowerShell job to import data, using enterprise Servers running older versions of PowerShell (It would be preferred if this can be done without importing any additional modules)
(Nice to have, but not necessary) Also interested to know if there's a way to report the success or failure of that job, to a log file?
This is the script I've tested in PowerShell 5, just can't use this on my older servers:
$database = 'DATABASE';
$server = 'SERVER';
$table = 'TABLE';
$MyData = import-csv \\TESTPATH\licenses_v2.csv -delimiter '|' |
select-object FirstName,LastName,Department,Title;
Write-DbaDataTable -sqlinstance $server -database $database -table $table -inputobject $MyData -KeepNulls;
The answer is yes, I just need to install the DBATools module.

PowerShell Silent Install Windows Application

To give the background, I’m trying to automate silent install of our Windows application (setup.exe) on a remote machine via PowerShell scripts and it is getting stuck due to a dependency, in our case SQLExpress Edition 2005.
Since our application depends on SQLExpress, during the installation process it tries to install the SQL Server 2005 Express Edition and that's when it gets stuck forever. I can see the process (SQLExpress**.exe) in Task Manager and nothing happens after that. However this works just fine when I logged in to the remote machine and do a manual installation (run setup.exe myself) as well as run through the PowerShell script locally (so that verify no issues with setup.exe or PowerShell script)
I tried different things but of no success. There are no logs or messages anywhere. All I know is, it is stuck while the setup launches the installation of SQLExpress.
Any help will be highly appreciated.
PowerShell command:
Start-Process -FilePath "C:[myapplicatonname]\setup.exe" -ArgumentList '-s -f2"c:\LogFiles\setup.log" -K"XXXXXXX-XXXX-XXXXX;XXXX-XXXX-XXXXXX" -gS' -Wait -PassThru
PS script to silent install application remotely:
$username = "[username]"
$password = "[pwd]"
$cred = new-object -typename System.Management.Automation.PSCredential ` -argumentlist $username, $password
$testCon = Test-Connection [machine name]
echo ($testCon + "==========================")
$dc1 = New-PSSession -ComputerName \\machinename -Credential $cred
Enter-PSSession -Session $dc1
$script = {
$p = Start-Process -FilePath "C:\[application name]\setup.exe" -ArgumentList '-s -f2"c:\LogFiles\setup.log" -K"1A34AQ9-SAHYTH-UMA68;JA34AQ9-YLMT-C7THH" -gS' -Wait -PassThru
}
invoke-command -computername \\machinename -Credential $cred -scriptblock $script
if($p.ExitCode -ne 0)
{
Write-Host " successfully installed"
}
else
{
Write-Host "installer exit code $($p.ExitCode)"
}
Exit-PSSession

How to Acess Remote Computer Folders in PS SQLSERVER:\>

Recently I came to know how to use Powersehll commands for executing SQL queries as mentioned below:
Import-Module “sqlps” -DisableNameChecking
$ds=Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $server -ConnectionTimeout $ConnectionTimeout -QueryTimeout $QueryTimeout
At this time Powershell ISE output Console will be in
PS SQLSERVER:\>
I was able to perform Select and Update queries without any error. The problem is faced when I wanted to access one of the file in remote computer. I tried to access the file as below:
PS SQLSERVER:\> Get-Content -Path \\Server\D$\Log\App.log
Even tried, just to list files/folders as
PS SQLSERVER:\> ls \\Server\D$\Log\
Iam getting below errors:
Get-Content : Cannot find path '\Server\D$\Log\App.log' because it does not exist.
ls : Cannot find path '\Server\D$\Log\' because it does not exist.
Need not to say- folder and file exists on that server as I was able to access the same when Powershell is running without SQL module. I mean console was showing just
PS C:\User\abc\
Sorry for this long story-- now, simple question!
How to access remote files/folders when Shell is in SQLSERVER console?
Thanks in Advance!
-Raj
You should be able to use the filesystem provider explicitly like this:
ls filesystem::\\server\d$\log
Just change your directory like so:
cd c:\
then:
ls \\server\d$\log
you can then change back to sql server by doing the same:
cd sqlserver:\
The powershell providers can be used just like you would a normal drive letter, pretty cool.
I believe it's running the commands remotely on the SQL server, which makes accessing data on another server from there a "double hop" scenario, and you'll need CredSSP auth for that to work.....

SqlService WMI query in PowerShell returns nothing

I'm trying to run a simple Get-WmiObject call in PowerShell.
Get-WmiObject -computerName $srv -namespace root\Microsoft\SqlServer\ComputerManagement -class SqlService
When running under an account that has administrator rights to the remote server I get no response. The command does complete, but no data is shown. When running this command under an account that does not have rights to the server I get an "Access Denied" message.
When I run this on the remote server directly I get "Invalid namespace", but the server is definitely our SQL Server 2008.
Why doesn't this kind of script return the object as expected?
Try
Get-WmiObject -computerName $srv -namespace root\Microsoft\SqlServer\ComputerManagement10 -class SqlService
On several machines I have, the namespace is ComputerManagement10.
BTW, just in case, you need to find the namespace names:
Get-WmiObject -ComputerName $srv -NameSpace root\Microsoft\SQLServer -Class "__NAMESPACE" | Select Name
The above command will tell you the right namespace names.
Have you checked services with get-service -computername $srv -include “*sql*”?
I would also check whether the class is present in:
Get-WmiObject -Namespace root\Microsoft\SqlServer\ComputerManagement10 -List

Resources