Filename not displaying in cmd - powershell

I have the following snippet
$svc_Files = gci | Where {$_.extension -eq ".svc"}
write-host "Building WSDL ..."
$cmd_svc = "`"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\SvcUtil.exe`""
Foreach ($svc_File in $svc_Files)
{
write-host "& $cmd_svc http://id.web/Services/$svc_File?wsdl"
}
The problem is that the file name is not displaying. However, once i remove "?wsdl", the filename displays.
How can I get the file name to display with "?wsdl" on the end?

write-host "& $cmd_svc http://id.web/Services/${svc_File}?wsdl"

Try this:
write-host "& $cmd_svc http://id.web/Services/$svc_File`?wsdl"
You could also do this:
write-host "& $cmd_svc http://id.web/Services/$($svc_File)?wsdl"

Related

Take Screenshot with Firefox

I'm having a heck of a time figuring out why this simple command is not working.
I'm attempting to take screenshots of a list of domains using PowerShell and Firefox per [this article][1].
Currently I have the following code, but it does not produce screenshots and I'm unsure what is wrong code wise. Any assistance and/or a point in the correct direction is greatly appreciated.
$screenshotdir = "$PSScriptRoot\FF_Screenshots"
If(!(Test-Path -Path $screenshotdir)) {New-Item -Path $PSScriptRoot -Name "FF_Screenshots" -ItemType Directory}
function getFireFoxScreenShot() {
$importedCSV = Import-Csv .\Domains.csv
foreach ($url in $importedCSV) {
$domainName = $url.Name #example google.com
$domain = $url.Domain #example google (no tld)
if (-not ([string]::IsNullOrEmpty($domainName))){
Echo "Getting Screen Shot for: $domainName"
Start-Process -FilePath "C:\Program Files\Mozilla Firefox\firefox.exe " -ArgumentList " --screenshot $screenshotdir\$domain.png ", "$domainName" -Wait
}
}
}
getFireFoxScreenShot
[1]: https://www.bleepingcomputer.com/news/software/chrome-and-firefox-can-take-screenshots-of-sites-from-the-command-line/
Make sure to specify protocol (https:// or http://) as it is in the article you linked to:
# Tested with Developer Edition of Firefox
$domain = "example"
$domainName = example.com"
$screenshotdir = "C:\SO\56572800"
# This works
Start-Process -FilePath "C:\Program Files\Firefox Developer Edition\firefox.exe" -ArgumentList "--screenshot $screenshotdir\$domain-with-https.png", "https://$domainName" -Wait
# But doesn't work
Start-Process -FilePath "C:\Program Files\Firefox Developer Edition\firefox.exe " -ArgumentList " --screenshot $screenshotdir\$domain-no-https.png ", "$domainName" -Wait
From what I checked, if you don't specify https:// prefix (or http:// if applicable), it'll hang for a long time so you might have an impression that it's working.
As #lloyd mentioned in comments, you have to make sure that value of $screenshotdir is properly assigned and available to the function.
Also, it's a good practice to trim leading/trailing spaces from your command, even though in your example it still works with the spaces. I mean these ones:
HERE | HERE | HERE |
Start-Process -FilePath "C:\Program Files\Mozilla Firefox\firefox.exe " -ArgumentList " --screenshot $screenshotdir\$domain.png ", "$domainName" -Wait

why does powershell script skip to the end?

I've got a little Powershell script that is supposed to deploy some service fabric applications locally:
I'm attempting to execute it like this:
.\Deploy.ps1 -ArtifactPath C:\packages\EnterpriseAPIPackages201710109749b
For some reason it skips to the last line of the script!
What am I doing wrong? How do I get all the lines to execute?
Param
(
[String]
$ArtifactPath
)
$LocalFolder = Split-Path -parent $MyInvocation.MyCommand.Path
$DeployScriptFile = "$LocalFolder\Scripts\Deploy-FabricApplication.ps1"
$ConfigFilePath = "$LocalFolder\config.xml"
$ConfigFilePath = Resolve-Path $ConfigFilePath
[Xml]$configParameters = (Get-Content $ConfigFilePath)
$services = $configParameters.DeploymentConfiguration.Microservices
if (!$ArtifactPath)
{
$ArtifactPath = $LocalFolder
}
$ApplicationPackageFiles = Get-ChildItem -Path $ArtifactPath -Filter ApplicationManifest.xml -Recurse -Force -ErrorAction SilentlyContinue
foreach($ApplicationPackageFile in $ApplicationPackageFiles)
{
$ApplicationPackagePath = Split-Path -Parent -Path $($ApplicationPackageFile.FullName)
$ProjectName = Split-Path $ApplicationPackagePath -Leaf
Write-Host "Start PowerShell script to deploy Microservice to Service Fabric: ApplicationPackageName: $($ProjectName)"
$ScriptBlock = [ScriptBlock]::Create("$DeployScriptFile -ApplicationPackagePath '$ApplicationPackagePath'")
Invoke-Command -ScriptBlock $ScriptBlock
}
Read-Host -Prompt "Press Enter to exit"
What am I doing wrong? How do I get all the lines to execute?
It seems there is nothing wrong with you code. I assume that there is nothing in the $ApplicationPackageFiles variable, so the foreach clause is not be executed.
You debug it with one of the following ways:
1.Print the $ApplicationPackageFiles variable to console directly
Write-Host "ApplicationPackageFiles value: $ApplicationPackageFiles"
2.Add the output info before and after foreach to check it.
Write-Host "Before loop..."
foreach($ApplicationPackageFile in $ApplicationPackageFiles)
{
xxxxx
}
Write-Host "After loop..."
I don't see anything immediately wrong with it. If you copy & pasted it from somewhere, the dashes, newlines, etc, might be wrong (especially if copy/pasting from rich text).
Open your script in PowerShell ISE or vscode and set a breakpoint at the top. Then you can step through line by line to narrow it down.
https://blogs.technet.microsoft.com/heyscriptingguy/2014/12/05/use-the-powershell-debugger/

file check script doesn't raise critical flag when file doesn't exist

I write a little script in PowerShell for Nagios that check if file exists.
If it exists the status should be "ok", and if not it should be "critical".
The problem is when the file does not exist the status is not "critical", it shows in Nagios as "unknown".
$path = "c:\test\test.txt"
$critical = 2
$ok = 0
if (-not (Test-Path $path)) {
Write-Host "file not exists"
exit $critical
} else {
Write-Host "file exists"
exit $ok
}
There's nothing wrong with your code, although I'd probably streamline it like this:
$path = "c:\test\test.txt"
$fileMissing = -not (Test-Path -LiteralPath $path)
$msg = if ($fileMissing) {'file does not exist'} else {'file exists'}
Write-Host $msg
exit ([int]$fileMissing * 2)
Your problem is most likely with the way you're executing the script. If you run the script using the -Command parameter, like this:
powershell.exe -Command "&{& 'C:\path\to\your.ps1'}"
or like this:
cmd /c echo C:\path\to\your.ps1 | powershell.exe -Command -
the return value is 1 if an error occured, or 0 otherwise, regardless of what exitcode you set.
To have PowerShell return the correct exit code you need to add an exit $LASTEXITCODE to the command string:
powershell.exe -Command "&{& 'C:\path\to\your.ps1'; exit $LASTEXITCODE}"
or call the script using the -File parameter:
powershell.exe -File "C:\path\to\your.ps1"

Run parameters in a Powershell script from a batch file

I'm trying to specify parameters in a powershell script, from a batch file.
The script itself looks likes this:
Param(
[Parameter(Mandatory=$true,HelpMessage="Application switch")]
[string[]]$Apps,
[ValidateRange(3,9999)]
[int]$SwitchDelay = 30
$AppPids = #()
$Windows = Get-Process | ? { $_.MainWindowTitle -ne "" }
$Wsh = New-Object -COM Wscript.Shell
foreach ($App in $Apps) {
foreach ($Window in $Windows) {
if ($Window.MainWindowTitle -like $App) {
Write-Verbose "Vindusfilter ""$App"" found hit on ""$($Window.MainWindowTitle)"" med PID ""$($Window.Id)"""
$AppPids += $Window.Id
}
}
}
do {
foreach ($ID in $AppPIDS) {
# Hides text...
$Wsh.AppActivate($ID) | Out-Null
Start-Sleep -Seconds $SwitchDelay
Write-Verbose "Changed window to PID ""$ID"""
}
} while ($true)
And what I'm trying to do is to define in a batch file is something like:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "C:\AppRotate.ps1" -Apps "*Chrome*", "Spotify*" -Switchdelay 5
pause
(Supposed to show error message here, need more reputation first...)
Error: "... PositionalParameterNotFound.Approtate.ps1"
I'm basically new to scripting, so any ideas?
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "C:\AppRotate.ps1" -Apps "*Chrome*","Spotify*" -Switchdelay 5
The problem was the space between the first, and second variable of parameter -Apps.
Should work now.

Powershell cannot bind parameter ForegroundColor

I have created the following Powershell script which I hope to use to copy files to a network share.
function Copy-Deploy
{
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Path to scripts")]
[Alias("pth")]
[string]$ScriptPath,
[Parameter(Position=1,Mandatory=$true,HelpMessage="Deployment script filename")]
[Alias("dep")]
[string]$PowershellDeploymentScript,
[Parameter(Position=2,Mandatory=$true,HelpMessage="MSI filename")]
[Alias("m")]
[string]$MSI,
[Parameter(Position=3,Mandatory=$true,HelpMessage="Filename of the MSBuild script (.btdfproj)")]
[Alias("msb")]
[string]$MSBuildScript,
[Parameter(Position=4,HelpMessage="UNC path to target server folder")]
[Alias("server")]
[string]$TargetServerPath
)
$ErrorActionPreference="Stop"
#Step 1 : copy the MSI, .btdfproj script and control powershell script to the remote server
Write-Host " Going to enter the mis script block"
$misScript =
{
Write-Host " Path+Filename = {0}({1})" -f $ScriptPath, $PowershellDeploymentScript
Write-Host " Going to copy files"
Write-Host " ScriptPath = $ScriptPath"
Write-Host " PowershellDeploymentScript = $PowershellDeploymentScript"
Write-Host " MSI = $MSI"
Write-Host " MSBuildScript = $MSBuildScript"
Write-Host " TargetServerPath = $TargetServerPath"
Copy-Item -Path "$ScriptPath" + "$PowershellDeploymentScript" -Destination "$TargetServerPath"
Copy-Item -Path "$ScriptPath" + "$MSI" -Destination "$TargetServerPath"
Copy-Item -Path "$ScriptPath" + "$MSBuildScript" -Destination "$TargetServerPath"
}
Invoke-Command -scriptblock $misScript
#Step2 : Execute the powershell script ExecuteBizTalkAppMSI.ps1 remotely on the target server
#using syntax... invoke-command -computer $MachineName -command { $TargetServerPath + ExecuteBizTalkAppMSI.ps1 }"
}
I run this script from the Powershell ISE with the following line:
Copy-Deploy "C:\Builds\3\x.Int.MIS\SupportBTDF\Sources\x.Int.MIS\Dev\V1.0\Src\Solutions\MIS\x.Int.MIS.Deployment\" "ExecuteBizTalkAppMSI.ps1" "bin\debug\x.Int.MIS-3.0.0.msi" "x.Int.MIS.Deployment.btdfproj" "\\d-vasbiz01\BizTalkDeployment"
I then get the following error:
Cannot bind parameter 'ForegroundColor'. Cannot convert value "C:\Builds\3\x.Int.MIS\SupportBTDF\Sources\x.Int.MIS\Dev\V1.0\Src\Solutions\MIS\x.Int.MIS.Deployment\,ExecuteBizTalkAppMSI.ps1" to type "System.ConsoleColor" due to invalid enumeration values. Specify one of the following enumeration values and try again. The possible enumeration values are "Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White".At C:\Builds\3\x.Int.MIS\SupportBTDF\Sources\x.Int.MIS\Dev\V1.0\Src\Solutions\MIS\x.Int.MIS.Deployment\CopyDeployScriptThenExecute.ps1:79 char:16
Could anyone please tell me where I went wrong?
The line :
Write-Host " Path+Filename = {0}({1})" -f $ScriptPath, $PowershellDeploymentScript
is the problem.
Write it like this:
Write-Host (" Path+Filename = {0}({1})" -f $ScriptPath, $PowershellDeploymentScript)
The -f was being taken as the -ForegroundColor parameter than the string format operator.
Wrap the message in parens. You can also use variable expansion and embed the variables without using the -format operator (like you did in other write-host calls):
Write-Host " Path+Filename = $ScriptPath($PowershellDeploymentScript)"