Extract a substring - powershell

I am trying to get proper error message which is there in description. But when my debugger enters into substring line its getting exited with no reason.
$job= submitting the job 2fdab2d5-f09c-4392-953e-8b85f90d76eb ...
client version: 10.2.2.0
target: cluster
stat: simulatelarge
skippath: true error submitting job.
vcclientexceptions.vcclientexception: [httpstatuscode = 0; description = e_csc_user_syntaxerror: syntax error. expected one of:_all _and ';' ')' ','
description: invalid syntax found in the script.
resolution: correct the script syntax, using expected token(s) as a guide.... at token [output], line 13 near the ###:
$descpos = $job.IndexOf("description:")
$resopos = $job.IndexOf("resolution:")
$descmsg = $descmsg.Substring($descpos)
Write-Host $descmsg
$ferrormsg = $job.Substring($msgpos,$respos+1)
Write-Host $ferrormsg
WORKING - CODE:
[string]$Result=$job
$Result= $Result -Replace "[\{]|(\{)|[\}]|(\})|[\""]|(\"")",''
$msgpos = $Result.IndexOf(("message:") )
$resopos = $Result.IndexOf(("resolution:") )
$descpos = $Result.IndexOf(("description:") )
$ferrormsg = $Result.Substring($msgpos,($descpos-$msgpos) )
$ferrormsg = $ferrormsg -Replace "(\,)|(\')|(\-)|(\=)",''
Write-Host $ferrormsg
THANKS ALL ,
Replaceing my string is working fine.

Try this
$job= "submitting the job 2fdab2d5-f09c-4392-953e-8b85f90d76eb ...
client version: 10.2.2.0
target: cluster
stat: simulatelarge
skippath: true error submitting job.
vcclientexceptions.vcclientexception: [httpstatuscode = 0; description = e_csc_user_syntaxerror: syntax error. expected one of:_all _and ';' ')' ','
description: invalid syntax found in the script.
resolution: correct the script syntax, using expected token(s) as a guide.... at token [output], line 13 near the ###:"
$descpos = $job.IndexOf("description:")
$resopos = $job.IndexOf("resolution:")
$ferrormsg = $job.Substring($descpos,$resopos-$descpos)
Write-Host $ferrormsg

Other solution :
$job= #"
submitting the job 2fdab2d5-f09c-4392-953e-8b85f90d76eb ...
client version: 10.2.2.0
target: cluster
stat: simulatelarge
skippath: true error submitting job.
vcclientexceptions.vcclientexception: [httpstatuscode = 0; description = e_csc_user_syntaxerror: syntax error. expected one of:_all _and ';' ')' ','
description: invalid syntax found in the script.
resolution: correct the script syntax, using expected token(s) as a guide.... at token [output], line 13 near the ###:
"#
$Result=$job -split "`n" | ? {$_ -like "*:*"} | %{$_.replace(':', '=')} | ConvertFrom-StringData
$Result.description

Related

How to use kubernetes python sdk to redeploy a deployment

version info:
python3.7
kubernetes==8.0.0
doc: https://github.com/kubernetes-client/python/tree/release-8.0/kubernetes
I only found the update API, not the redeploy API。
thanks
If you want to partially update an existing deployment use PATCH method. An example below
# create an instance of the API class
api_instance = kubernetes.client.AppsV1Api(kubernetes.client.ApiClient(configuration))
name = 'name_example' # str | name of the Deployment
namespace = 'namespace_example' # str | object name and auth scope, such as for teams and projects
body = NULL # object |
pretty = 'pretty_example' # str | If 'true', then the output is pretty printed. (optional)
dry_run = 'dry_run_example' # str | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed (optional)
try:
api_response = api_instance.patch_namespaced_deployment(name, namespace, body, pretty=pretty, dry_run=dry_run)
pprint(api_response)
except ApiException as e:
print("Exception when calling AppsV1Api->patch_namespaced_deployment: %s\n" % e)
If you want to replace the existing deployment with a new deployment use PUT method. An example below
# create an instance of the API class
api_instance = kubernetes.client.AppsV1Api(kubernetes.client.ApiClient(configuration))
name = 'name_example' # str | name of the Deployment
namespace = 'namespace_example' # str | object name and auth scope, such as for teams and projects
body = kubernetes.client.V1Deployment() # V1Deployment |
pretty = 'pretty_example' # str | If 'true', then the output is pretty printed. (optional)
dry_run = 'dry_run_example' # str | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed (optional)
try:
api_response = api_instance.replace_namespaced_deployment(name, namespace, body, pretty=pretty, dry_run=dry_run)
pprint(api_response)
except ApiException as e:
print("Exception when calling AppsV1Api->replace_namespaced_deployment: %s\n" % e)

Setting output variable using newman / postman is getting cut off

I have an output variable siteToDeploy and siteToStop. I am using postman to run a test script against the IIS Administration API. In the test portion of one of the requests I am trying to set the azure devops output variable. Its sort of working, but the variable value is getting cut off for some reason.
Here is the test script in postman:
console.log(pm.globals.get("siteName"))
var response = pm.response.json();
var startedSite = _.find(response.websites, function(o) { return o.name.indexOf(pm.globals.get("siteName")) > -1 && pm.globals.get("siteName") && o.status == 'started'});
var stoppedSite = _.find(response.websites, function(o) { return o.name.indexOf(pm.globals.get("siteName")) > -1 && o.status == 'stopped'});
if(stoppedSite && startedSite){
console.log('sites found');
console.log(stoppedSite.id)
console.log('##vso[task.setvariable variable=siteToDeploy;]' + stoppedSite.id);
console.log('##vso[task.setvariable variable=siteToStop;]' + startedSite.id);
}
Here is the output form Newman:
Here is the output from a command line task echoing the $(siteToDeploy) variable. It's getting set, but not the entire value.
I've tried escaping it, but that had no effect. I also created a static command line echo where the variable is set and that worked fine. So I am not sure if it is a Newman issue or Azure having trouble picking up the varaible.
The issue turned our to be how Azure is trying to parse the Newman console log output. I had to add an extra Powershell task to replace the ' coming back from the Newman output.
This is what is looks like:
##This task is only here because of how Newman is writing out the console.log
Param(
[string]$_siteToDeploy = (("$(siteToDeploy)") -replace "'",""),
[string]$_siteToStop = (("$(siteToStop)") -replace "'","")
)
Write-Host ("##vso[task.setvariable variable=siteToDeploy;]{0}" -f ($_siteToDeploy))
Write-Host ("##vso[task.setvariable variable=siteToStop;]{0}" -f ($_siteToStop))

Importing a Powershell Module as LocalSystem Account on TeamCity

I've got some strange behavior between me running a command under my profile, and TeamCity running the same command.
> Import-Module $root\packages\fsm.buildrelease.*\tools\modules\BuildDeployModules -Force
If I run the script manually, the build kicks off as expected. If I let TeamCity execute the script, it pukes with the following.
Import-Module : The specified module 'C:\BuildAgent\work\81eb7c2fdfcfc0af\packages\fsm.buildrelease.*\tools\modules\BuildDeployModules' was not loaded because no valid module file was found in any module directory.
I have double and triple verified that the module exists in that location. And I've gone through my modules and added [cmdletbinding()] before the param, but it doesn't seem to solve this issue.
It's frustrating because it doesn't say "which" module is getting an invalid parameter passed in.
$fsmbrVersion = "1.1.1" # contains the current version of fsm.buildrelease
Write-Host "`nfsm.buildrelease version $fsmbrVersion `nCopyright ($([char]0x00A9)) Future State Mobile Inc. & Contributors`n"
Push-Location $psScriptRoot
. .\Add-HostsFileEntry.ps1
. .\Add-IISHttpVerb.ps1
. .\Add-IISMimeType.ps1
. .\Add-LoopbackFix.ps1
. .\ApplicationAdministration.ps1
. .\AppPoolAdministration.ps1
. .\Approve-Permissions.ps1
. .\Assert-PSVersion.ps1
. .\EntityFramework.ps1
. .\Expand-NugetPackage.ps1
. .\Expand-ZipFile.ps1
. .\Format-TaskNameToHost.ps1
. .\Get-EnvironmentSettings.ps1
. .\Grunt.ps1
. .\Helpers.ps1
. .\Install-WebApplication.ps1
. .\Invoke-Deployment.ps1
. .\Invoke-DeployOctopusNugetPackage.ps1
. .\Invoke-ElevatedCommand.ps1
. .\Invoke-ExternalCommand.ps1
. .\Invoke-Using.ps1
. .\MSBuild.ps1
. .\Nuget.ps1
. .\nUnit.ps1
. .\Set-IISAuthentication.ps1
. .\Set-IISCustomHeader.ps1
. .\SiteAdministration.ps1
. .\Specflow.ps1
. .\SqlHelpers.ps1
. .\Test-PathExtended.ps1
. .\Test-RunAsAdmin.ps1
. .\TextUtils.ps1
. .\Update-AssemblyVersions.ps1
. .\Update-JsonConfigFile.ps1
. .\Update-XmlConfigFile.ps1
. .\WindowsFeatures.ps1
. .\xUnit.ps1
Pop-Location
Export-ModuleMember `
-Alias #(
'*') `
-Function #(
'Add-HostsFileEntry',
'Add-IISHttpVerb',
'Add-IISMimeType',
'Add-LoopbackFix',
'Approve-Permissions',
'Assert-That',
'Assert-PSVersion',
'Confirm-ApplicationExists',
'Confirm-AppPoolExists',
'Confirm-SiteExists',
'Exec',
'Expand-NugetPackage',
'Expand-ZipFile',
'Format-TaskNameToHost',
'Get-Application',
'Get-Applications',
'Get-AppPool',
'Get-AppPools',
'Get-DatabaseConnection',
'Get-EnvironmentSettings',
'Get-Site',
'Get-Sites',
'Get-TestFileName',
'Get-WarningsFromMSBuildLog',
'Get-WindowsFeatures',
'Install-WebApplication',
'Install-WindowsFeatures',
'Invoke-BulkCopy',
'Invoke-DBMigration',
'Invoke-Deployment',
'Invoke-DeployOctopusNugetPackage',
'Invoke-ElevatedCommand',
'Invoke-EntityFrameworkMigrations',
'Invoke-ExternalCommand',
'Invoke-FromBase64',
'Invoke-GruntMinification',
'Invoke-HtmlDecode',
'Invoke-HtmlEncode',
'Invoke-KarmaTests',
'Invoke-MSBuild',
'Invoke-Nunit',
'Invoke-NUnitWithCoverage'
'Invoke-SpecFlow',
'Invoke-SqlFile',
'Invoke-SqlStatement',
'Invoke-ToBase64',
'Invoke-UrlDecode',
'Invoke-UrlEncode',
'Invoke-Using',
'Invoke-XUnit',
'Invoke-XUnitWithCoverage',
'New-Application',
'New-AppPool',
'New-NugetPackage',
'New-Site',
'Remove-Application',
'Remove-AppPool',
'Remove-Site',
'RequiredFeatures',
'Set-IISAuthentication',
'Set-IISCustomHeader',
'Start-Application',
'Start-AppPool',
'Start-Site',
'Step',
'Stop-Application',
'Stop-AppPool',
'Stop-Site',
'Test-PathExtended',
'Test-RunAsAdmin',
'Update-Application',
'Update-AppPool',
'Update-AssemblyVersions',
'Update-JsonConfigValues',
'Update-Site',
'Update-XmlConfigValues'
)
# Messages
DATA msgs {
convertfrom-stringdata #"
error_duplicate_step_name = Step {0} has already been defined.
error_must_supply_a_feature = You must supply at least one Windows Feature.
error_feature_set_invalid = The argument `"{0}`" does not belong to the set `"{1}`".
error_admin_required = You are required to 'Run as Administrator' when running this deployment.
error_loading_sql_file = Error loading '{0}'. {1}.
error_octopus_deploy_failed = Failed to deploy: {0}.
error_specflow_failed = Publishing specflow results for '{0}' failed.
error_coverage_failed = Running code coverage for '{0}' failed.
error_tests_failed = Running tests '{0}' failed.
error_msbuild_compile = Error compiling '{0}'.
wrn_full_permission = You have applied FULL permission to '{0}' for '{1}'. THIS IS DANGEROUS!
wrn_cant_find = Could not find {0} with the name: {0}.
msg_grant_permission = Granting {0} permissions to {1} for {2}.
msg_enabling_windows_feature = Enabling Windows Feature: `"{0}`".
msg_wasnt_found = `"{0}`" wasn't found.
msg_updated_to = Updated `"{0}`" to `"{1}`".
msg_updating_to = Updating `"{0}`" to `"{1}`".
msg_changing_to = Changing `"{0}`" to `"{1}`".
msg_overriding_to = Overriding node `"{0}`" with value `"{1}`".
msg_updating_assembly = Updating AssemblyVersion to '{0}'. Updating AssemblyFileVersion to '{1}'. Updating AssemblyInformationalVersion to '{2}'.
msg_not_updating = Not updating {0}, you must specify the '-updateIfFound' if you wish to update the {0} settings.
msg_custom_header = Setting custom header '{0}' on site '{1}' to value '{2}'.
msg_disable_anon_auth = Disabling Anonymous Authentication for '{0}'.
msg_web_app_success = Successfully deploy Web Application '{0}'.
msg_copying_content = Copying {0} content to {1}.
msg_use_machine_environment = Using config for machine {0} instead of the {1} environment.
msg_octopus_overrides = Checking for Octopus Overrides for environment '{0}'.
msg_teamcity_importdata = ##teamcity[importData type='{0}' tool='{1}' path='{2}']
msg_teamcity_buildstatus = ##teamcity[buildStatus text='{0}']
msg_teamcity_buildstatisticvalue = ##teamcity[buildStatisticValue key='{0}' value='{1}']
msg_add_loopback_fix = Adding loopback fix for '{0}'.
msg_add_mime_type = Adding mime type '{0}' for extension '{1}' to IIS site '{2}'.
msg_add_verb = Adding IIS Http Verb '{0}' to site '{1}'.
msg_add_host_entry = Adding host entry for '{0}' into the hosts file.
msg_validate_host_entry = Validating host entry for '{0} in the hosts file'
msg_loopback_note = note: we're not disabling the loopback check all together, we are simply adding '{0}' to an allowed list.
"#
}
The problem is nothing to do with importing the module; powershell isn't very helpful in leading you to the issue. The root of the issue didn't reveal it's self until I put the -VERBOSE switch on the import. Once I did that, I got a new error above the old one.
: Parameter attributes need to be a constant or a script block.
FullyQualifiedErrorId: ParameterAttributeArgumentNeedsToBeConstandOrScriptBlock
Essentially, I was using ValidatePattern with double quotes instead of single quotes. Check and make sure your writing your regex patterns correctly when you use ValidatePattern
# Bad
[ValidatePattern("^[a-z]$")]
# Good
[ValidatePattern('^[a-z]$')]

Hash entry sometime is $NULL (error), and sometimes isn't?

I have my little 3-sided socket-server. Each server has its own hash with its key-values.
The very first is:
$Local = #{ID="Local"; ...}
$RemtA = #{ID="RemtA"; ...}
$RemtB = #{ID="RemtB"; ...}
I start for all of the the listeners - no problem.
If now a client wants to connect, I want to add the ID to $ProgressHead, which is defined like this:
$ProgressHead = "Value-Broadcast, Connected: "
and used in my function to accept a client called with its hash as $h:
if ( !$h.Connected ) {
#Write-Host "$($h.ID) not connected, pending: $($h.listener.Pending())"
if ( $h.listener.Pending()) {
$h.client = $h.listener.AcceptTcpClient() # will block here until connection
$h.stream = $h.client.GetStream();
$h.writer = New-Object System.IO.StreamWriter $h.stream
$h.writer.AutoFlush = $true
$h.Connected = $true
Write-Host $Global:ProgressHead # fails - empty ??
Write-Host $h.ID # prints oh depit it is marked as error
if ( !$Global:ProgressHead.Contains( $h.ID ) ) { # <= HERE IS THE ERROR ????
$Global:ProgressHead= "$($Global:ProgressHead)$($h.ID) "
}
}
}
The Error message says:
Can't call a method for an expression which is NULL and $h.ID is underlined
BUT I DO NOT get any error if I start this either in the cmd-console when running powershell -file ThreeServer.ps1 or within the ISE in debug mode. The ID is written correctly to $ProgressHead!
Only if I start this in the Powershell console (PS C:\...> ./ThreeServer.ps1) I get this error, but all the other keys in the lines above are valid ONLY $h.ID on ONLY the PS-console throws this error?

PowerShell webdeploy

I'm trying to use PowerShell with web deployment based on this
article
This is how my script looks like
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Deployment")
function Sync-Provider($provider, $sourceLocation, $destLocation)
{
$destBaseOptions = new-object Microsoft.Web.Deployment.DeploymentBaseOptions
$syncOptions = new-object Microsoft.Web.Deployment.DeploymentSyncOptions
Try
{
$deploymentObject = [Microsoft.Web.Deployment.DeploymentManager]::CreateObject($provider, $sourceLocation)
$deploymentObject.SyncTo($provider,$destLocation,$destBaseOptions,$syncOptions)
}
Catch
{
echo "EXCEPTION THROWN::[ $_ ] "
#throw $_
}
}
Sync-Provider ("apphostConfig","D:\NerdDinner_2.0\NerdDinner","c:\inetpub\wwwroot")
Running this gives the following exception
EXCEPTION THROWN::[ Cannot convert argument "0", with value: "System.Object[]",
for "CreateObject" to type "Microsoft.Web.Deployment.DeploymentWellKnownProvid
er": "Cannot convert value "apphostConfig,D:\NerdDinner_2.0\Ne
rdDinner,c:\inetpub\wwwroot" to type "Microsoft.Web.Deployment.DeploymentWellKn
ownProvider" due to invalid enumeration values. Specify one of the following en
umeration values and try again. The possible enumeration values are "Unknown, A
ppHostConfig, AppHostSchema, AppPoolConfig, ArchiveDir, Auto, Cert, ComObject32
, ComObject64, ContentPath, CreateApp, DirPath, DBFullSql, DBMySql, FilePath, G
acAssembly, IisApp, MachineConfig32, MachineConfig64, Manifest, MetaKey, Packag
e, RecycleApp, RegKey, RegValue, RootWebConfig32, RootWebConfig64, RunCommand,
SetAcl, WebServer, WebServer60"." ]
Could you give me some hints on this, please?
Try to enclose the first parameter [Microsoft.Web.Deployment]::DeploymentWellKnownProvider.AppHostConfig with a pair of extra parenthesis: ([Microsoft.Web.Deployment]::DeploymentWellKnownProvider.AppHostConfig).
In my case I had the same problem, just opened the powershell console as Administrator and it worked.