run powershell script from sql server agent (type: powershell) - sql

I am trying to run simple powershell script prom a job(sql server agent).
script:
[string]$SrcFolder = "G:\MSSQL\Test";
[string]$TrgFolder = "\\xx.xx.xx.xxx\d$\sql\logshipping" ;
if (-not(Get-Module -Name SQLPS))
{
if (Get-Module -ListAvailable -Name SQLPS) {
Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location
};
};
if ($SrcFolder -eq $null -or $TrgFolder -eq $null )
{
Write-Host "The source Folder = $SrcFolder ,OR target folder = $TrgFolder is not valid/Null";
};
$prafix = "[A-Za-z]+_[0-9]+_[0-9].trn" ;
Set-Location -Path C:\ ;
# Copy to Destination
foreach ($file in gci -Path $SrcFolder | Where-Object{ $_.Mode -eq '-a---' -and $_.Extension -eq '.trn' -and $_.Name -match $prafix})
{
write-host "Starting Copy File: $($file.FullName) ." ;
Copy-Item -Path $file.FullName -Destination $TrgFolder -Force -ErrorAction Stop ;
if (Test-Path -LiteralPath "$TrgFolder\$($file.Name)")
{
write-host "End Copy File: $($file.FullName) ." ;
Move-Item -Path $file.FullName -Destination "$SrcFolder\Moved" -Force ;
}
else
{
Write-Host "The Copy File: $TrgFolder\$($file.BaseName) . Failed "
};
}
The script doing: Copy .bak files to remote server. then check if the bak file exists in the remote server, and if it's exists his move the bak file to a local folder .
The job is failing message:
Date 9/1/2016 6:29:31 PM Log Job History (LS_Manual-Copy)
Step ID 3 Server SQL2012ENT-IR-3 Job Name LS_Manual-Copy Step
Name Delete Old Logs Duration 00:00:00 Sql Severity 0 Sql Message
ID 0 Operator Emailed Operator Net sent Operator Paged Retries
Attempted 0
Message Unable to start execution of step 3 (reason: line(23): Syntax
error). The step failed.
the sql server agent is a member in the Administrator group .
please help .
10X

Related

Unable to create Log Alert using New-AzActivityLogAlert

We are trying to automate the creation of log alerts using the Az.Monitor library and getting the following error
New-AzActivityLogAlert : The module 'Az.Monitor.internal' could not be loaded. For more information, run 'Import-Module Az.Monitor.internal'.
At E:\Code\Code\ManageLogAnalyticsAlerts.ps1:28 char:5
New-AzActivityLogAlert -Name 'sometest' -ResourceGroupName $logWo ...
CategoryInfo : ObjectNotFound: (Az.Monitor.inte...ctivityLogAlert:String) [New-AzActivityLogAlert], CommandNotFoundException
FullyQualifiedErrorId : CouldNotAutoLoadModule,New-AzActivityLogAlert
The code that we are using is
$receiverName = $actionGroupName
$actionGroupReceiver = New-AzActionGroupReceiver -Name $receiverName -EmailReceiver -EmailAddress 'emailstub#email.com' -UseCommonAlertSchema -WarningAction silentlyContinue
$actionGroup = Set-AzActionGroup -Name $actionGroupName -ResourceGroup $logWorkspace.ResourceGroupName -ShortName $actionGroupName -Receiver $actionGroupReceiver -WarningAction silentlyContinue
Write-Host '----Action Group: ' $actionGroupName ', Action Group Id: ' $actionGroup.Id ', created with Action Group Receiver: ' $receiverName ' in the log workspace: ' $logWorkspace.Name
$activityGroupObject = New-AzActivityLogAlertActionGroupObject -Id $actionGroup.Id -WebhookProperty #{"sampleWebhookProperty"="SamplePropertyValue"}
$scope = "subscriptions/"+(Get-AzContext).Subscription.ID
$condition1=New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject -Equal Ingestion -Field category
# $condition2=New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject -Equal Error -Field level
$any1=New-AzActivityLogAlertAlertRuleLeafConditionObject -Field properties.Operation -Equal 'Data collection"'
$any2=New-AzActivityLogAlertAlertRuleLeafConditionObject -Field properties.incidentType -Equal Incident
$condition3=New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject -AnyOf $any1,$any2
New-AzActivityLogAlert -Name 'sometest' -ResourceGroupName $logWorkspace.ResourceGroupName -Action $activityGroupObject -Condition #($condition1,$condition3) -Location global -Scope $scope
The line which is causing the error is
New-AzActivityLogAlert -Name 'sometest' -ResourceGroupName $logWorkspace.ResourceGroupName -Action $activityGroupObject -Condition #($condition1,$condition3) -Location global -Scope $scope
The Powershell version we have is
$PSVersionTable
Name Value
---- -----
PSVersion 5.1.18362.628
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.18362.628
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
The Az Powerhshell version that I have is 9.0.1.
Apparently, this was a bug, and the Azure team will be deploying the fix to production. Here is the link https://github.com/Azure/azure-powershell/issues/19927 which gives the timeline.

Authenticate Azure Blob Storage Account in cloud using a runbook

In AZURE ANALYSIS SERVICES Tabular model (with compatibility level 1400) I imported a Blob storage account as a Data Source. It's Authentication Kind is Key kind of authentication. The key is a Static Key.
But while refreshing the Tabular using a Runbook in Automation Account (Cloud PowerShell) is there a way to pass the key/credentials so that it could authenticate?
Otherwise the PowerShell fails with below message
The given credential is missing a required property. Data source kind: AzureBlobs. Authentication kind: Key. Property name: Key. The exception was raised by the IDbConnection interface.
Here is the Source definition copied from Model.bim file:
{
"createOrReplace": {
"object": {
"database": "azureanalysisservicesdatabase",
"dataSource": "OMSLogs"
},
"dataSource": {
"type": "structured",
"name": "OMSLogs",
"connectionDetails": {
"protocol": "azure-blobs",
"address": {
"account": "storage",
"domain": "blob.core.windows.net"
},
"authentication": null,
"query": null
},
"credential": {
"AuthenticationKind": "Key",
"kind": "AzureBlobs",
"path": "https://storage.blob.core.windows.net/",
"PrivacySetting": "Organizational"
}
}
}
}
this is the code I ran in PowerShell to process the Database:
Invoke-ProcessASDatabase -databasename $DatabaseName -server $AnalysisServerName -RefreshType "Full" -Credential $SPCredential
Okay I also hit a similar issue and found the solution, add "Key" to the "credential" object:
"credential": {
"AuthenticationKind": "Key",
"kind": "AzureBlobs",
"path": "https://storage.blob.core.windows.net/",
"PrivacySetting": "Organizational",
"Key": "<StorageAccountKey>"
}
This isn't well documented by Microsoft, but this worked for me
Update with PowerShell sample:
Get-ChildItem -Filter "drop" -Recurse -Path $sourcePath -Directory |
Get-ChildItem -recurse -filter *.asdatabase -file | ForEach-Object {
$filename = $_.fullname
$generatedFile = $buildPath + $_.BaseName + ".xmla"
"Processing $filename"
& $deploymentWizard $filename /o:$generatedFile
# Have to add Blob Key now, as Deployment Wizard doesn't like
# adding the Key (bug maybe? Or DeloyWizard isn't up to date)
$file = Get-Content $generatedFile -Raw | ConvertFrom-Json
$file.createOrReplace.database.model.dataSources | ForEach-Object {
# Add Blob Key to credential object
if ($_.name.StartsWith("AzureBlobs/")) {
$_.credential | Add-Member -Name "Key" -Value $storageKey -MemberType NoteProperty -Force
}
}
$file = $file | ConvertTo-Json -Depth 32
$file | Set-Content -Path $generatedFile -Encoding utf8
}

How to connect and create a file on a distant PC using SSH and EXPECT script?

When i run my program, this loop should copy my files $file in my directories $dir. First of all, it is just creating a new file named $file in my $myDest (And it is not creating a new directory $dir to put my $file in it).
foreach file $FILES dir $DIRECTORIES {
set timeout -1;
puts "\nFichier : $file \n"
puts "Repertoire : $dir \n"
spawn scp -p -r "$mySource/$file" "$myDest/$dir"
expect -re "(.*)assword: " {sleep 1; send -- "$pass\r" }
expect -timeout 3600 eof
}
So i tried to add the command mkdir to all this stuff so it create me the directory on the distant PC but its does not work.
foreach file $FILES dir $DIRECTORIES {
set timeout -1;
puts "\nFichier : $file \n"
puts "Repertoire : $dir \n"
spawn ssh marpic#192.168.110.90 'mkdir $path/$dir'
expect -re "(.*)assword: " {sleep 1; send -- "$pass\r" }
expect eof
spawn scp -p -r "$mySource/$file" "$myDest/$dir"
expect -re "(.*)assword: " {sleep 1; send -- "$pass\r" }
expect -timeout 3600 eof
}
Error code :
root#raspberrypi:~# ./recupRaspFiles.sh
Fichier : 2018-03-07_09-34-24_R_HOURS_Q2
Repertoire : 2018-03-07
spawn ssh marpic#192.168.110.90 'mkdir /home/marpic/muonic_data/Data_Q2/2018-03-07'
marpic#192.168.110.90's password:
bash: mkdir /home/marpic/muonic_data/Data_Q2/2018-03-07: Aucun fichier ou dossier de ce type
spawn scp -p -r /root/muonic_data/2018-03-07_09-34-24_R_HOURS_Q2 marpic#192.168.110.90:/home/marpic/muonic_data/Data_Q2/2018-03-07
[...]
Does anyone have a solution ?

Is that possible to use "Invoke-SqlCmd" as a part of Visual Studio Online build step?

We try to get our DB updated as part of the Visual Studio Online build as dedicated build step, but the PowerShell script that we locally using fails to work on the hosted build controller with following error.
2015-07-28T20:35:26.8546681Z ##[error]import-module : The specified module 'sqlps' was not loaded because no valid module file was found in any module
2015-07-28T20:35:26.8546681Z ##[error]directory.
Is there any way to use "Invoke-SqlCmd" in VSO hosted build controller?
Got it working with those lines!
Add-PSSnapin SqlServerCmdletSnapin100 -ErrorAction SilentlyContinue
Add-PSSnapin SqlServerProviderSnapin100 -ErrorAction SilentlyContinue
Here how I do it:
$moduleName = "SqlServer"
if (Get-Module $moduleName -ListAvailable) {
Write-Host "Module '$moduleName' is available"
} else {
Write-Host "Module '$moduleName' does not exist"
try {
Install-Module -Name $moduleName -Force -AllowClobber
Write-Host "Module '$moduleName' successfully installed"
} catch {
Throw "Installation of module '$moduleName' failed: $($_.Exception)"
}
}

PSake Error Executing MSBuild Command

I have 3 projects in the solution,
A WPFApplication and 2 ClassLibrary projects
When i build the Solution i get error below..
properties {
$base_dir = resolve-path .
$build_dir = "$base_dir\build"
$buildartifacts_dir = "$build_dir\BuildArtifacts"
$sln_file = "$base_dir\Hello.sln"
}
task default -depends Compile
task Clean {
Write-Host "Cleaning solution" -ForegroundColor Green
remove-item -force -recurse $buildartifacts_dir -ErrorAction
SilentlyContinue
}
task Init -depends Clean {
Write-Host "Creating BuildArtifacts directory" -ForegroundColor Green
new-item $buildartifacts_dir -itemType directory
}
task Compile -depend Init {
Write-Host "Compiling ---" $sln_file -ForegroundColor Green
Exec { msbuild $sln_file "/p:OutDir=$build_artifacts_dir"
/p:Configuration=Release /v:quiet }
}
i get the following error's -- what am i doing wrong?
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2868­,9):
error MSB3023: No destination specified for Copy. Please supply either "DestinationFiles" or "DestinationFolder". [D:\Nusrofe\GrokPSake2\ClassLibrary1\ClassLibrary1.csproj]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(3471­,9):
error MSB4044: The "FindUnderPath" task was not given
a value for the required parameter "Path". [D:\Nusrofe\GrokPSake2\ClassLibrary1\ClassLibrary1.csproj]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2868­,9):
error MSB3023: No destination specified for Copy. Ple
ase supply either "DestinationFiles" or "DestinationFolder". [D:\Nusrofe\GrokPSake2\ClassLibrary2\ClassLibrary2.csproj]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(3471­,9):
error MSB4044: The "FindUnderPath" task was not given
a value for the required parameter "Path". [D:\Nusrofe\GrokPSake2\ClassLibrary2\ClassLibrary2.csproj]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(3471­,9):
error MSB4044: The "FindUnderPath" task was not given
a value for the required parameter "Path". [D:\Nusrofe\GrokPSake2\WpfApp\WpfApp.csproj]
build2.ps1:Error executing command: msbuild $sln_file
"/p:OutDir=$build_artifacts_dir" /p:Configuration=Release /v:quiet
Thanks --
Corku
Looks like in your Compile task you have a stray underscore in your $buildartifacts_dir variable. MSBuild probably doesn't know what to do because essentially you are passing it an empty location for the OutDir.