What does "$?" mean in PowerShell - variables

I'm very new to PowerShell. While looking up information about error handling I've found a lot of references to using "$?"
I know that it has something to do with errors but what exactly is it? And where can I read more about it?
All of my Google searches have found nothing.

From the The Essential Windows PowerShell Cheat Sheet:
Errors and Debugging: The success or failure status of the last command can be determined by checking $?
Example:
> Get-Content file-that-exists.txt
Hello world
> Write-Host $?
True
> Get-Content file-that-does-not-exist.txt
Get-Content : Cannot find path 'C:\file-that-does-not-exist.txt' because it does not exist.
At line:1 char:1
+ Get-Content file-that-does-not-exist.txt
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\file-that-does-not-exist.txt:String) [Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
> Write-Host $?
False

Just after asking this I discovered the command
"Get-Help -name about_automatic_variables"
This gives information about every automatic variable in powershell, it's very helpful

Related

How to install Microsoft SQL server as userdata(powershell) on windows machine in AWS? or powershell error resolution for below

Its and windows machine and trying to install Sql Server(unattended) using powershell
Write-Host "`nStarting the install of SQL Server" -ForegroundColor Green
[string]$userName = 'domain\username'
[string]$userPassword = 'xyz'
[securestring]$secStringPassword = ConvertTo-SecureString $userPassword -AsPlainText -Force
[pscredential]$credObject = New-Object System.Management.Automation.PSCredential ($userName, $secStringPassword)
Start-Process -Filepath "$driveLetter\setup.exe" -ArgumentList "/ConfigurationFile=`"$temp_file_location`"" -Credential $credObject -NoNewWindow -Wait -RedirectStandardOutput $standardOutputFile -RedirectStandardError $errorOutputFile
ERROR:
PS C:\Windows\system32> C:\Users\manish\Desktop\custommain.ps1
domain
eu-west-1
fetching the password from parameter stores
Cleaning the outputfile error
finding and replacing the domains and secrets
writting the content of ini into temp file C:\xyz-softwares\ms-sql-server\scripts\batch-files\temp_ConfigurationFile.ini
Mounting SQL Server Image
Getting Disk drive of the mounted image
Starting the install of SQL Server
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
At C:\xyz-softwares\ms-sql-server\scripts\powershell\ms-sqlserver-installation.ps1:65 char:2
+ Start-Process -Filepath "$driveLetter\setup.exe" -ArgumentList "/ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
SQL Installation Failed Installation with exit code
SQL Installation Failed Installation with exit code
At C:\xyz-softwares\ms-sql-server\scripts\powershell\ms-sqlserver-installation.ps1:72 char:9
+ throw $error_message
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (SQL Installatio... with exit code:String) [], RuntimeException
+ FullyQualifiedErrorId : SQL Installation Failed Installation with exit code
PS C:\Windows\system32>
I have tried with powershell with domain credentials.
Although i have exe file and windows machine is connected with domain
Tried to start process command with domain credetials.

Running flume agent to get Twitter data

I have been trying to run a flume agent on my windows system to get twitter data. I am following this blog
https://acadgild.com/blog/streaming-twitter-data-using-flume
But, whenever i try to run the flume agent I get the follwing error -
flume-ng agent -n TwitterAgent -f ./conf/flume.conf
E:\apache-flume-1.7.0-bin\apache-flume-1.7.0-bin\bin>powershell.exe -NoProfile -InputFormat none -ExecutionPolicy unrestricted -File E:\apache-flume-1.7.0-bin\apache-flume-1.7.0-bin\bin\flume-ng.ps1 agent -n TwitterAgent -f ./conf/flume.conf
Resolve-Path : Cannot find path 'E:\apache-flume-1.7.0-bin\apache-flume-1.7.0-bin\bin\conf\flume.conf' because it does not exist.
At E:\apache-flume-1.7.0-bin\apache-flume-1.7.0-bin\bin\flume-ng.ps1:217 char:24 + $confFile = '"' + (Resolve-Path $confFile).Path + '"' + ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (E:\apache-flume...conf\flume.conf:String) [Resolve-Path], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand
I have tried debugging it on my own, but have failed to do so. I tried to look for this particular error but could not find it anywhere.
Does E:\apache-flume-1.7.0-bin\apache-flume-1.7.0-bin\bin\conf\flume.conf exist at that location? Are you sure it's in \bin\conf\flume.conf and not \conf\flume.conf? In which case use:
flume-ng agent -n TwitterAgent -f ./../conf/flume.conf
Or (as is more common), run from the E:\apache-flume-1.7.0-bin\apache-flume-1.7.0-bin folder with the command:
bin/flume-ng agent -n TwitterAgent -f ./conf/flume.conf

windows PowerShell ISE multi scripts (remove - zip - rename)

I would like delete a folder named pdf3.wgt after that .zip content of a folder (where was this pdf3.wgt) and finaly rename it in pdf3.wgt, (with windows PowerShell ISE).
prerequisite: C:\wamp64\www\pdf3\pdf3.wgt file exist
When i run (f5) this scripts created by the PowerShell ISE with module Compress-Archive and Rename-Item:
Remove-Item -Path C:\wamp64\www\pdf3\pdf3.wgt
PS C:\Users\tonys> Compress-Archive -DestinationPath C:\wamp64\www\pdf3\pdf3.zip -Path C:\wamp64\www\pdf3
PS C:\Users\tonys> Rename-Item -NewName pdf3.wgt -Path C:\wamp64\www\pdf3\pdf3.zip
in PowerShell ISE on windows 10 i got this error:
`PS C:\Users\tonys> rmdir C:\wamp64\www\pdf3\pdf3.wgt
PS C:\Users\tonys> Compress-Archive -DestinationPath C:\wamp64\www\pdf3\pdf3.zip -Path C:\wamp64\www\pdf3
PS C:\Users\tonys> Rename-Item -NewName pdf3.wgt -Path C:\wamp64\www\pdf3\pdf3.zip
Get-Process : A positional parameter cannot be found that accepts argument 'Compress-Archive'.
At line:2 char:1
+ PS C:\Users\tonys> Compress-Archive -DestinationPath C:\wamp64\www\pd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetProcessCommand
Get-Process : A positional parameter cannot be found that accepts argument 'Rename-Item'.
At line:3 char:1
+ PS C:\Users\tonys> Rename-Item -NewName pdf3.wgt -Path C:\wamp64\www\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetProcessCommand`
Could someone tell me why use module proposed by powershell d'ont work ?
adn why he said to me '
A positional parameter cannot be found that accepts argument ?
'
++
When creating a script by copying from an interactive session do not include the command prompt.
PS C:\Users\tonys> Compress-Archive -DestinationPath C:\wamp64\www\pdf3\pdf3.zip -Path C:\wamp64\www\pdf3
PS is an alias for Get-Process and its arguments bare no resemblance to the rest of the line.

SQL CleanUp Job to delete old backup files in shared folder

I tried the following three ways to clean-up the old backup files but none of them is worked. We need your help on this to complete.
Way 1: Created Maintenance Cleanup Job, the job successful executed but backup was not deleted the files.
Way 2: Tried using xp_delete_file command.
Script Used:
EXECUTE master.sys.xp_delete_file 0,N'\\XXX\YYY',N'bak',N'2014-05-12T07:34:14'
Error Message:
Executed as user: DOMAIN\user. The process could not be created for
step 3 of job 0x307C7663CBCA6D4187B1953745E1E02F (reason: The system
cannot find the file specified). The step failed.
Way 3: Tried using the power shell script
Script Used:
$Path = "\\xxx\yyy"
$Daysback = "-30"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse -include *.bak| Where-Object { $_.LastWriteTime -lt $DatetoDelete } | remove-item -force
Error Message:
Executed as user: DOMAIN\user.. The job script encountered the
following errors.
These errors did not stop the script: A job step received an error at
line 9 in a PowerShell script.
The corresponding line is 'Get-ChildItem $Path -Recurse -include
*.txt, *.bak| Where-Object { $_.LastWriteTime -lt $DatetoDelete } | remove-item -force'. Correct the script and reschedule the job. The
error information returned by PowerShell is: 'Cannot find path
'\xxx\yyy' because it does not exist. '. Process Exit Code 0. The
step succeeded.
The Powershell script was executed successfully in powershell window but not in the powershall task. also i have created proxy account which user has permission over the shared path and used the poroxy account to run the tasks.
Please help me to solve the issue.
There needs to be a back slash at the end of the path name, so '\\XXX\YYY' needs to be '\\XXX\YYY\' (note the extra backslash) - so the command becomes:
EXECUTE master.sys.xp_delete_file 0,N'\\XXX\YYY\',N'bak',N'2014-05-12T07:34:14'

Error when calling 3rd party executable from Powershell when using an IDE

I have a PowerShell script that uses du.exe (Disk Usage originally from Sysinternals) to calculate the size of directories.
If I run du c:\Backup in the console, it works as expected, but the same line of code run in ISE or PowerGui gives the expected result plus the error
+ du <<<< c:\backup
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Why is that? How do I avoid this error? I tried invoke-expression, using &, but no go.
Thanks for the help.
Another way to suppress the NativeCommandError output is to convert the objects in the pipeline to strings as outlined at the bottom of this answer:
du c:\Backup 2>&1 | %{ "$_" }
To avoid this you can redirect stderr to null e.g.:
du 2> $null
Essentially the console host and ISE (as well as remoting) treat the stderr stream differently. On the console host it was important for PowerShell to support applications like edit.com to work along with other applications that write colored output and errors to the screen. If the I/O stream is not redirected on console host, PowerShell gives the native EXE a console handle to write to directly. This bypasses PowerShell so PowerShell can't see that there are errors written so it can't report the error via $error or by writing to PowerShell's stderr stream.
ISE and remoting don't need to support this scenario so they do see the errors on stderr and subsequently write the error and update $error.
I've recently been facing the same issues, but I would like to get the stderr output directed to stdout. You would think that the following would work:
& du 2>&1
But PowerShell will interpret the redirection and process it after 'du' is completed. The work-around I found is to invoke it using cmd.exe /c:
& cmd /c 'du 2>&1'
Previous FIX will redirect errors but you could lose a real error if by example your user name or password is not good or if using integrated authentication, you do not have access.
So here is a way to implement the error handling and bypass the specific error (that is not one) raised by psexec.
try {
whoami # powershell commands
}
catch [System.Management.Automation.RemoteException] {
if ($_.TargetObject -like "Connecting to *" -and $_.CategoryInfo.Category -eq "NotSpecified" -and $_.FullyQualifiedErrorId -eq "NativeCommandError" -and $_.InvocationInfo.MyCommand.Name -like "psexec*.exe") {
$error.Remove[$Error[0]]
}
else {
Throw
}
}
catch {
throw
}
After pulling a load of hair out, I realised that actually, these errors only occur when running the .ps1 file from "Windows PowerShell ISE".
When I ran the same .ps1 script from a Command Line, the errors didn't happen.
powershell.exe .\MikesScript.ps1
Write this script at the top of your PowerShell script it will solve this issue and even it will not affect the whole behavior of all error commands
#prepare powershell for docker-compose commands
if((select-string -Path $profile -Pattern "Set-Alias docker-compose 'docker-compose.cmd'") -eq $null ){
Add-Content -Path $profile -Value "Set-Alias docker-compose 'docker-compose.cmd'"}
$str = "#echo off
docker-compose.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 2>&1"
if ((Get-Content "C:\Windows\System32\docker-compose.cmd" -ErrorAction Ignore) -ne $str){
$str.Trim() | Out-File "C:\Windows\System32\docker-compose.cmd" -Encoding ascii}