I am trying to invoke Msdeploy in powershell , which is part of a teamcity build task.
My script is like this below
$folderName = "packageTmp"
$packagePath = (gci -path %teamcity.build.checkoutDir%\extract -filter $foldername -Recurse | Select-Object -Expand FullName) |Out-String
$azureSite ="%azureSite%"
$azurePublishUrl = "%azurePublishUrl%"
$azureUsername ="%azureUsername%"
$azurePassword = "%azurePassword%"
$localPath =$packagePath
$server ="https://$azurePublishUrl/msdeploy.axd?site=$azureSite,UserName=$azureUsername,Password=$azurePassword,AuthType=Basic"
$remotePath="%azureSite%"
$env:Path += ";C:\Program Files\IIS\Microsoft Web Deploy V3"
function PushToTarget() {
param([string]$server, [string]$remotePath, [string]$localPath)
cmd.exe /C $("msdeploy.exe -verb:sync -source:contentPath=`"{0}`" -dest:computerName=`"{1}`",contentPath=`"{2}`" -whatif" -f $localPath, $server, $remotePath )
}
echo "Server: " $server
echo "remote path: " $remotePath
echo "local path: " $localPath
PushToTarget "$server" "$remotePath" "$localPath"
while i run this i get following error , error stack follows
Error: A '-dest' argument must be specified with the 'sync' verb.
As error says i have included sync keyword already.
what i am doing wrong and how can i rectify it ?
i tried to use following solutions
solution1
stackoverflow post
I don't see a problem in your script but PS can be particular.
Here is how the new ASP.NET 5 PS-based deployment executes MSDeploy.exe maybe this will work better for you:
$webrootOutputFolder = (get-item (Join-Path $packOutput $webroot)).FullName
$publishArgs = #()
$publishArgs += ('-source:IisApp=''{0}''' -f "$webrootOutputFolder")
$publishArgs += ('-dest:IisApp=''{0}'',ComputerName=''{1}'',UserName=''{2}'',Password=''{3}'',IncludeAcls=''False'',AuthType=''Basic''{4}' -f
$publishProperties['DeployIisAppPath'],
(Get-MSDeployFullUrlFor -msdeployServiceUrl $publishProperties['MSDeployServiceURL']),
$publishProperties['UserName'],
$publishPwd,
$sharedArgs.DestFragment)
$publishArgs += '-verb:sync'
$publishArgs += '-enableLink:contentLibExtension'
$publishArgs += $sharedArgs.ExtraArgs
$command = '"{0}" {1}' -f (Get-MSDeploy),($publishArgs -join ' ')
if (! [String]::IsNullOrEmpty($publishPwd)) {
$command.Replace($publishPwd,'{PASSWORD-REMOVED-FROM-LOG}') | Print-CommandString
}
Execute-Command -exePath (Get-MSDeploy) -arguments ($publishArgs -join ' ')
Related
I've got a macro looping with powershell and at the end of a run to clean up it kills and restarts the browser, Standard FireFox version firefox.exe
Using:
taskkill /F /IM firefox.exe /T
How can I prevent it from killing the dev version of FireFox too, which has the same executable name?
EDIT:
I was asked to post the code
Link to the original script from github https://github.com/A9T9/RPA/blob/2501e8cbc504160e2aab89a7e35ece9fcf2873e1/command-line/powershell/run%20one%20macro%20forever.ps1
This script shows how to run a macro "forever"
by checking on the command line return value
and killing/restarting Browser if needed
function PlayAndWait ([string]$macro)
{
$timeout_seconds = 300
$path_downloaddir = "C:\Users\xxxx\ui-logs\"
$path_autorun_html = "C:\Users\xxxxx\UIVision Powershell Script\ui.vision.html"
$log = "log_" + $(get-date -f MM-dd-yyyy_HH_mm_ss) + ".txt"
$path_log = $path_downloaddir + $log
$browser = 2
Switch ($browser) {
1 {$cmd = "${env:Program Files(x86)}\Google\Chrome\Application\chrome.exe"; break}
2 {$cmd = "${env:ProgramFiles}\Mozilla Firefox\firefox.exe"; break} #For FIREFOX
}
$arg = """file:///"+ $path_autorun_html + "?macro="+ $macro + "&direct=1&closeRPA=1&closeBrowser=1&savelog="+$log+""""
Start-Process -FilePath $cmd -ArgumentList $arg #Launch the browser and run the macro
$status_runtime = 0
Write-Host "Log file will show up at " + $path_log
while (!(Test-Path $path_log) -and ($status_runtime -lt $timeout_seconds))
{
Write-Host "Waiting for macro to finish, seconds=" $status_runtime
Start-Sleep 10
$status_runtime = $status_runtime + 10
}
if ($status_runtime -lt $timeout_seconds)
{
$status_text = Get-Content $path_log -First 1
$status_int = -1
If ($status_text -contains "Status=OK") {$status_int = 1}
}
else
{
$status_text = "Macro did not complete within the time given:" + $timeout_seconds
$status_int = -2
}
remove-item $path_log #clean up
return $status_int, $status_text, $status_runtime
}
$testreport = "C:\xxxx\ui-logs\uireport.txt"
For ($i=0; $i -le 9999; $i++) {
Write-Host "Loop Number:" $i
$result = PlayAndWait MyMacro-04-2022 #run the macro
$errortext = $result[1] #Get error text or OK
$runtime = $result[2] #Get runtime
$report = "Loop:" + $i + " Return code: " + $result[0]+ " Macro runtime: "+$runtime+" seconds, Result: "+ $errortext
Write-Host $report
Add-content $testreport -value ($report)
if ($result[0] -ne 1)
{
taskkill /F /IM firefox.exe /T
$report = "Loop:" + $i + " Firefox closed"
Add-content $testreport -value ($report)
}
}
Assuming Developer edition is installed in the default directory of "C:\Program Files\Firefox Developer Edition\firefox.exe"
Get-Process Firefox | ?{$_.path -notmatch "dev"} | Stop-Process -Force
Alternatively you can use the exe file description field
Get-Process Firefox | ?{$(Get-ItemProperty -Path $_.Path).VersionInfo.FileDescription -notmatch "Developer"} | Stop-Process -Force
edit: to kill the whole process tree as per this post:
function Kill-Tree {
Param([int]$ppid)
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq $ppid } | ForEach-Object { Kill-Tree $_.ProcessId }
Stop-Process -Id $ppid
}
Get-Process Firefox | ?{$(Get-ItemProperty -Path $_.Path).VersionInfo.FileDescription -notmatch "Developer"} | %{Kill-Tree $_.Id}
i have a script made in powershell and i am using nssm to create as a service to be executed every "x" time, however when starting the service it generates error and does not execute.
I have full administrator rights and I even tried to run PowerShell as an administrator without success.
If I run the script directly it works, however using nssm it is not working.
The error that happens is this:
Start-Service: Service 'nice (nice)' start failed.
At C: \ Program Files \ NICE Systems \ nssm.ps1: 10 char: 14
Start-Service <<<< $ serviceName
CategoryInfo: OpenError: (System.ServiceProcess.ServiceController: ServiceController) [Start-Service],
ServiceCommandException
FullyQualifiedErrorId: StartServiceFailed, Microsoft.PowerShell.Commands.StartServiceCommand
nssm.ps1
$nssm = (Get-Command nssm.exe).Definition
$serviceName = 'nice'
$powershell = (Get-Command powershell.exe).Definition
$scriptPath = 'C:\Program Files\NICE Systems\script_delecao.ps1'
$arguments = '-ExecutionPolicy Bypass -NoProfile -File "{0}"' -f $scriptPath
& $nssm install $serviceName $powershell $arguments
& $nssm status $serviceName
Start-Service $serviceName
Get-Service $serviceName
script_delecao.ps1
$logPath = "C:\Program Files\NICE Systems\Logs\*\Archive\*"
# -------------------------------------------------------------------------------------------
# SET $NDAYS WITH THE NUMBER OF DAYS TO KEEP IN LOG FOLDER.
$nDays = 180
# -------------------------------------------------------------------------------------------
# SET $EXTENSIONS WITH THE FILE EXTENSION TO DELETE.
# YOU CAN COMBINE MORE THAN ONE EXTENSION: "*.LOG, *.TXT,"
$Extensions = "*.log*"
# -------------------------------------------------------------------------------------------
# PAY ATTENTION! IF YOU COMBINE MORE THAN ONE LOG PATH AND EXTENSIONS,
# MAKE SURE THAT YOU ARE NOT REMOVING FILES THAT CANNOT BE DELETED
# -------------------------------------------------------------------------------------------
$PathDelete = "C:\Program Files\NICE Systems\Delecoes"
while ($true) {
If(!(test-path $PathDelete))
{
New-Item -ItemType Directory -Force -Path $PathDelete
}
$LogDate = (Get-Date).ToString("dd_MM_yyyy")
$DateTime = (Get-Date).ToString("yyy-MM-ddThh:mm:ss")
$Files = Get-Childitem $LogPath -Include $Extensions -Recurse | Where `
{$_.LastWriteTime -le (Get-Date).AddDays(-$nDays)}
foreach ($File in $Files)
{
if ($File -ne $NULL)
{
$Log = $DateTime + " - O arquivo " + $File + " foi deletado "
$Log | Out-File -Append $PathDelete\DeleteLogFile_$LogDate.log
Remove-Item $File.FullName| out-null
}
}
# Add a sleep at the end of the loop to prevent the script from eating
# too much CPU time
$Log = $DateTime + " FINAL DO ARQUIVO "
$Log | Out-File -Append $PathDelete\DeleteLogFile_$LogDate.log
Start-Sleep -Seconds 300
}
I believe I have a similar scenario where I cannot back-up Bamboo file system while it's running. My back-up executes from a rundeck server via Remote PowerShell, and even though the user has local admin rights it cannot stop and start services using NSSM. So I use this function to run the command elevated
ELEVAT "nssm stop bamboo"
tar --exclude=./logs --exclude=./temp --exclude=*.log --exclude=*.jar --verbose -czf E:\dropfolder\bamboo-home.tar.gz --directory=E:\bamboo-home .
ELEVAT "nssm start bamboo"
the function itself...
function ELEVAT ($command) {
$scriptBlock = [scriptblock]::Create($command)
configuration elevated {
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
Set-StrictMode -Off
Node localhost {
Script execute {
SetScript = $scriptBlock
TestScript = {
if (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Verbose "Verified Elevated Session"
return $false
} else {
Write-Verbose "Not an Elevated Session!"
exit 9996
}
}
GetScript = { return #{ 'Result' = 'RUN' } }
}
}
}
$mof = elevated
Start-DscConfiguration ./elevated -Wait -Verbose -Force
if ( $error ) { Write-Host "[ELEVAT][WARN] `$Error[] = $Error" ; $Error.clear()
}
}
I inherited this script from my precursor, which is supposed to copy a bunch of files from one location into a JFrog Artifactory.
It workes fine except for files with followed by an H in the name.
For example Test My Client.exe will be copied correctly but Test My Host.exe will be ignored by the script.
Anybody has an idea what the reason for this strange behaviour is?
param
(
[string]$RootPath="D:\_temp\upload\",
[string]$Repo="repo-snapshot",
[string]$Product="SEARCHER",
[string]$Version="1.23.45678.9012",
[string]$ArtifactoryRoot
)
$AF_USER = "myUser"
$AF_PWD = "pA55VVoRd" #ConvertTo-SecureString "pA55VVoRd" -AsPlainText -Force
$CREDS = New-Object System.Management.Automation.PSCredential ($AF_USER, $AF_PWD)
$MajorMinor = $Version.Split('.')[0] + "." + $Version.Split('.')[1]
$BuildRevision = $Version.Split('.')[2] + "." + $Version.Split('.')[3]
$uri = "https://artifactory.test.com/artifactory/$Repo/TEST/$Product/$MajorMinor/$BuildRevision/$ArtifactoryRoot/"
$curl = "$PSScriptRoot\..\..\bin\ReleaseU\curl.exe"
Write-Host $MajorMinor
write-host $BuildRevision
$filesToUpload = Get-ChildItem $RootPath -Recurse -File
foreach($file in $filesToUpload)
{
$artifactoryAddPath = $file.FullName.Remove(0,$RootPath.Length).Replace('\','/')
$completeUrl = $uri+$artifactoryAddPath
write-host $completeUrl
$FileSize = (Get-Item $file.FullName).Length /1MB
Write-Host "Filesize: "$FileSize" MB"
$preTime = Get-Date
write-host "$curl --user $AF_USER`:$AF_PWD --upload-file " $file.FullName "$completeUrl --insecure"
. $curl --user $AF_USER`:$AF_PWD --upload-file $file.FullName $completeUrl --insecure
$postTime = Get-Date
Write-Host "Upload finished"
$timeDiff = $postTime - $preTime
$avgSpeed = $FileSize / $timeDiff.TotalSeconds
Write-Host -Object ("Upload speed is: {0:N2}MB/sec" -f ($avgSpeed));
}
I wrote a PowerShell script to automate deployment of SSAS Cubes. I use the Deployment Wizard to generate an XMLA file and then PowerShell AMO command to deploy it. However, when I run it the tabular database gets created but all measures are missing. Running the same XMLA from SQL Management Studio or using Invoke-ASCmd produce the correct database with all measures in it. Am I missing an option or something in the "Invoke" command?
[CmdletBinding()]
Param(
# InputDir is required
[Parameter(Mandatory=$True,Position=1)]
[string]$InputDir,
# Server is optional
[Parameter(Mandatory=$False,Position=2)]
[string]$Server=$env:computername
)
# Output execution parameters.
"Executing with the following parameters:"
" InputDir: $InputDir"
" AS Database Server: $Server`n"
$XmlaDir = Resolve-Path($InputDir)
$Xmla = Join-Path -Path $XmlaDir -ChildPath '\Model.xmla'
$ASFiles = Get-ChildItem -Recurse -Path $InputDir -Filter *.asdatabase
$Count = $ASFiles.Count
If($Count -ne 1)
{
Write-Host("`ERROR: Count asdatabase file(s) found at $inputdir")
Exit 1
}
$ASDatabase = $ASFiles[0].FullName
Write-Host("`nUsing $ASDatabase for deployment.")
Write-Host("`nAttempting to create $Xmla ...`n")
# Use Analysis Services Deployment Utility to generate XMLA file from
.asdatabase file
$Script:ASDeployWizard = "E:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\Microsoft.AnalysisServices.Deployment.exe
"
$Arguments = #("`"$ASDatabase`"", "/s", "/o:`"$Xmla`"")
Start-Process -FilePath $Script:ASDeployWizard -ArgumentList $Arguments -Wait
If ((-Not $?) -Or -Not (Test-Path $Xmla))
{
"Cannot generate deployment descriptor. Deployment aborted."
Exit 1
}
Write-Host("XMLA deployment descriptor generated.`n")
Try {
Import-Module SQLPS -DisableNameChecking
# Deploy Cube
"Invoking deployment script. This may take several minutes...`n"
$AS = New-Object Microsoft.AnalysisServices.Server
$AS.connect($Server)
$CubeDescriptor = [string](Get-Content $Xmla)
$Results = $AS.Execute($CubeDescriptor)
Foreach ($r in $Results) {
$r.Messages.Description
}
"Done.`n"
} Catch {
Write-Host($_.Exception.GetType().FullName + "`n" + $_.Exception.Message + "`n")
Write-Host("Deployment FAILED.`n")
}
Exit 0
I am trying to output the following command to a text file in powershell, but I cannot seem to get it working:
ssh -v git#git.assembla.com | Out-File C:\output.txt
As stated in the post below with using native apps, you could try using Start-Process, e.g.
Start-Process ssh "-v git#git.assembla.com" -NoNewWindow -RedirectStandardOutput stdOut.log -RedirectStandardError stdErr.log; gc *.log; rm *.log
Working on the same problem I made a detail post on my blog How to SSH from Powershell Using Putty\Plink but the short version is this bit of code. But sure you try it after installing putty.
Function Invoke-SSHCommands {
Param($Hostname,$Username,$Password, $CommandArray, $PlinkAndPath, $ConnectOnceToAcceptHostKey = $true)
$Target = $Username + '#' + $Hostname
$plinkoptions = "-ssh $Target -pw $Password"
#Build ssh Commands
$remoteCommand = ""
$CommandArray | % {$remoteCommand += [string]::Format('{0}; ', $_) }
#plist prompts to accept client host key. This section will login and accept the host key then logout.
if($ConnectOnceToAcceptHostKey)
{
$PlinkCommand = [string]::Format('echo y | & "{0}" {1} exit', $PlinkAndPath, $plinkoptions )
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
}
#format plist command
$PlinkCommand = [string]::Format('& "{0}" {1} "{2}"', $PlinkAndPath, $plinkoptions , $remoteCommand)
#ready to run the following command
#Write-Host $PlinkCommand
$msg = Invoke-Expression $PlinkCommand
$msg
}
$PlinkAndPath = "C:\Program Files (x86)\PuTTY\plink.exe"
$Username = "remoteshell"
$Password = "pa$$w0rd"
$Hostname = "Linuxhost"
$Commands = #()
$Commands += "ls"
$Commands += "whoami"
Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands