PowerShell script inside SQL Agent job error - powershell

I'm trying to run the code below via a script in a SQL agent job on a drive which is failing. When I logon as the service account user and run it in an ISE shell it works fine which leads me to believe it's not access related.
I tried running it as a PowerShell job step but it wouldn't work so decided to run it as a cmdexec job type and call it like this:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file "F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1"
Script
$ComputerName = "servername"
$KeyFolder = "\\servername\sharename\SSRSKEYS\"
$KeyPassword = "Password1"
$TimeStamp = Get-Date -Format "-yyyyMMdd-HHmmss"
Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer" -Class "__Namespace" -ComputerName $ComputerName |
Select-Object -ExpandProperty Name |
% {
$NameSpaceRS = $_
$InstanceName = $NameSpaceRS.SubString(3)
$KeyFileName = Join-Path -Path $KeyFolder -ChildPath ($InstanceName + $Timestamp + ".snk")
$SQLVersion = (Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer\$($NameSpaceRS)" -Class "__Namespace" - ComputerName $ComputerName).Name
$SSRSClass = Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer\$($NameSpaceRS)\$($SQLVersion)\Admin" - Query "SELECT * FROM MSReportServer_ConfigurationSetting WHERE InstanceName='$($InstanceName)'" -ComputerName $ComputerName
$Key = $SSRSClass.BackupEncryptionKey($KeyPassword)
If ($Key.HRESULT -ne 0) {
$Key.ExtendedErrors -join "`r`n" | Write-Error
} Else {
$Stream = [System.IO.File]::Create($KeyFileName, $Key.KeyFile.Length)
$Stream.Write($Key.KeyFile, 0, $Key.KeyFile.Length)
$Stream.Close()
}
}
Error
Executed as user: domain\svc_account. Exception calling "Create" with "2"
argument(s): "Access to the path '\\servername\sharename\SSRSKEYS\MSSQLSERVER-20150824-125254.snk' is denied." At
F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1:24 char:13 + $Stream = [System.IO.File]::Create($KeyFileName, $Key.KeyFile.Length ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +
CategoryInfo : NotSpecified: (:) [], MethodInvocationException +
FullyQualifiedErrorId : UnauthorizedAccessException You cannot call a
method on a null-valued expression. At
F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1:25 char:13 +
$Stream.Write($Key.KeyFile, 0, $Key.KeyFile.Length) +

Try passing the script path to the PowerShell.exe as a parameter using the & operator, e.g.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "& 'F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1'"
The call operator (&) allows you to execute a command, script or function.
Syntax
& "[path] command" [arguments]

Related

Powershell activate Windows 10 WMIMethodException

I'm trying to activate Windows 10 with PowerShell.
I got the following script:
$computerName = $env:COMPUTERNAME
$key = "[Windows 10 product key is in here]"
$activationService = Get-WmiObject -Query "select * from SoftwareLicensingService" -ComputerName $computerName
$activationService.InstallProductKey($key)
$activationService.RefreshLicenseStatus()
But I keep getting the following exception:
Exception calling "InstallProductKey" : ""
At F:test.ps1:4:1
+ $activationService.InstallProductKey($key)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
I just can't seem to get this right.
The syntax is correct!
I used the following to activate my notebook
$computer = gc env:computername
$key = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
$service = get-wmiObject -query "select * from SoftwareLicensingService" -computername $computer
$service.InstallProductKey($key)
$service.RefreshLicenseStatus()
Launch cmd as Administrator and run:
slmgr.vbs /ipk xxxxx-xxxxx-xxxxx-xxxxx-xxxxx

WMI Scripting Windows 8 error

I have a problem with WMI in a machine with a Windows 8 Home Edition. I need to catch the CPU usage and the ProcessID by process. I've tried so many ways:
ShellExecute in Delphi
A *.bat with the code
A *.vbs
A *.vbs executed by a *.bat
A *.ps1
A *.ps1 executed by a *.bat
(Maybe some of these ways can be really stupid, but I've tried anyway)
In the User-Click it works perfectally, but by a standalone applicantion it doesn't work.
I have opened the Security on WMIMGMT.msi of some folders and the execution policy (in PowerShell) now is UNRESTRICTED.
This is the code on the *.ps1 file:
$ErrorActionPreference = "SilentlyContinue"
Stop-Transcript | Out-Null
$ErrorActionPreference = "Continue"
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
foreach ($p in $peflist) {
"" + $p.IDProcess + ";" + $p.PercentProcessTime
}
This is the code on *.bat
powershell -ExcetutionPolicy Unrestricted -File "C:\Somefolder\PP.ps1" > C:\SomeFolder\output.txt
All I got is this output:
get-wmiobject : Invalid query "select * from Win32_Win32_PerfFormattedData_PerfProc_Process"
In C:\Somefolder\PP.ps1:4 character: 14
+ $perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErroID : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Edit1: The code copied as asked:
*.ps1:
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
foreach ($p in $perflist) {
"" + $p.IDProcess + ";" + $p.PercentProcessorTime
}
*.bat
powershell -executionPolicy unrestricted -file "C:\MonitorPerformance\test.ps1" > C:\MonitorPerformance\output1.txt
Output: (Consulta inválida = Invalid Query; No = in; caractere = character)
get-wmiobject : Consulta inv lida "select * from Win32_PerfFormattedData_PerfProc_Process"
No C:\MonitorPerformance\test.ps1:4 caractere:14
+ $perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
replace this:
$perflist = (get-wmiobject Win32_Win32_PerfFormattedData_PerfProc_Process)
with this:
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
Windows 8 does not performs WMI actions perfectly when you use x32 applications, I made a dummy x64 application who executes the *.bat and it finally works. Thanks for all the help.

Property is empty when run through Invoke-Command

I am trying to individually monitor memory usage of a process (w3wp.exe) that has multiple instances of itself by filtering out a string found in the process' CommandLine property.
It works when I run this script locally:
$proc = (WmiObject Win32_Process -Filter "Name = 'w3wp.exe'" | Where-Object {$_.CommandLine -like "*SomeTextFromCl*"})
$id = $proc.ProcessId
$ws = [math]::round((Get-Process -Id $id).WS/1MB)
Write-Host $ws
However, when I try to run it remotely through Invoke-Command, I get an error telling that the Id property's value is null:
Cannot bind argument to parameter 'Id' because it is null.
+ CategoryInfo : InvalidData: (:) [Get-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetProcessCommand
+ PSComputerName : RemoteServerName
My Invoke-Command syntax is:
Invoke-Command -ComputerName RemoteServerName -FilePath script.ps1 -Credential $mycredential
I'm sure it's simple but I'm back to PS after a long absence and I had a look around but couldn't find anything really helpful.
You are writing the answer to the console. You use the ps1 as a function, so you should use:
return $ws
instead of
write-host $ws

how to add data from a file to an open variable in powershell

I am trying to add an open varible to this command so when the data pulls from line 24 it adds it to the variable and makes it executable.
$data = Get-Content "C:\Users\bgriffiths\Documents\test.dat"
$data[24]
I have tried adding different formats to do this and nothing seems to work.
one command i tried was
invoke-command sql -query = $data
I get an error telling me
Invoke-Command : A parameter cannot be found that matches parameter name 'query'.
At line:4 char:26
+ invoke-command sql -query <<<< = $data
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
another command I have been trying to run is
$Command.CommandType.text = $data
the only error I get from this is
Property 'text' cannot be found on this object; make sure it exists and is settable.
At line:10 char:30
+ $Command.CommandType. <<<< text = $data
+ CategoryInfo : InvalidOperation: (text:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
I am at a lost on how to import file data into the script and have it run it.
I figured out how to run commands for sql through my powershell I had to actaully import the assembly list for the sql ps and then I was able to run the Invoke-SqlCmd
the script to add the information for sqlps to your windows ps is -
$ErrorActionPreference = "Stop"
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
throw "SQL Server Powershell is not installed."
}
else
{
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}
#
# Preload the assemblies. Note that most assemblies will be loaded when the provider
# is used. if you work only within the provider this may not be needed. It will reduce
# the shell's footprint if you leave these out.
#
$assemblylist =
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.Dmf ",
"Microsoft.SqlServer.SqlWmiManagement ",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.SmoExtended ",
"Microsoft.SqlServer.Management.RegisteredServers ",
"Microsoft.SqlServer.Management.Sdk.Sfc ",
"Microsoft.SqlServer.SqlEnum ",
"Microsoft.SqlServer.RegSvrEnum ",
"Microsoft.SqlServer.WmiEnum ",
"Microsoft.SqlServer.ServiceBrokerEnum ",
"Microsoft.SqlServer.ConnectionInfoExtended ",
"Microsoft.SqlServer.Management.Collector ",
"Microsoft.SqlServer.Management.CollectorEnum"
foreach ($asm in $assemblylist)
{
$asm = [Reflection.Assembly]::LoadWithPartialName($asm)
}
#
# Set variables that the provider expects (mandatory for the SQL provider)
#
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
#
# Load the snapins, type data, format data
#
Push-Location
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location
Write-Host -ForegroundColor Yellow 'SQL Server Powershell extensions are loaded.'
Write-Host
Write-Host -ForegroundColor Yellow 'Type "cd SQLSERVER:\" to step into the provider.'
Write-Host
Write-Host -ForegroundColor Yellow 'For more information, type "help SQLServer".'
the link where I found this is http://blogs.msdn.com/b/mwories/archive/2008/06/14/sql2008_5f00_powershell.aspx

powershell invoke-command does not work if I use -computerName

I want to execute below code in the either local or remote machine whith current user.
$BackUpSqlAgentAndRemoveOldbackup = {
param([string]$AppServer,[string]$SqlInstance,[string]$BackupShare,[string]$alias)
[Environment]::UserName #I got same user name in all cases.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $SqlInstance
$backupName = 'SqlAgentJob_' + $SqlInstance + '_' + (Get-Date –format ‘yyyyMMdd_HHmm’) + '_' + $alias + '.sql'
$backupPath = join-path $BackupShare $backupName
$oldBackups = Get-ChildItem $backupShare | where { ( $_.name -like 'SqlAgentJob_*.sql' ) }
$server.JobServer.Jobs.Script() | Out-File -filepath $backupPath
foreach ( $item in $oldBackups ) { remove-item $item.fullName }
}
the #argList is
#('hafcapp-1', 'hafcsql-1', '\\Host5FileSrv\Backup\test','auto')
I notice that
this one, it works well (no -comupterName and -session)
Invoke-Command -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
this one, it throw execption (I also tried "-session", get same result)
Invoke-Command -computerName localhost -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
the exception is as below, it seems the it can not access the folder.
Cannot find path '\\Host5FileSrv\Backup\test' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\Host5FileSrv\Backup\test:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (Script:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Remove-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand
does anyone know how can I do if I want to add computerName or session?
(notes:[Environment]::UserName return identical user)
You have run into the double hop problem. Your credentials can be transferred to the next machine (first hop), but no further (second hop). This means that you can't use the credentials of the machine where you are executing Invoke-Command on, the remote machine (localhost) to connect to a file share (\Host5FileSrv\Backup). Even if you use localhost as computername, it is still remoting. A solution could be CredSSP. See here and here for more information.
This looks like a "second hop" remoting problem, and you'll need to configure WinRM on the computers involved to use CredSSP
http://msdn.microsoft.com/en-us/library/windows/desktop/ee309365(v=vs.85).aspx