How do I set up autocomplete in powershell 2.0? - forms

I have a drop down menu that's populated by a CSV file. I had to change my code around to make it work with v2. The last thing I can't figure out is autocomplete. I'd like to be able to type in the listbox and have it suggest some options from the list. It works fine in v3, but not v2.
Here are the parts that matter...
$filecheck = "$dir\Apps\Customers.csv"
If(Test-Path -path $filecheck) {
$Customers = Import-CSV "$dir\Apps\Customers.csv" -Header $headers
$List = $customers | Select-Object -Expand name | where {$_ -ne ""} | where {$_ -ne "Name"} | Sort-Object
}
ForEach ($Items in $List) {
$companybox.Items.Add($Items)
}
$companybox.AutoCompleteSource = 'CustomSource'
$companybox.AutoCompleteMode = 'SuggestAppend'
$List | % {$companybox.AutoCompleteCustomSource.AddRange($_) }
$Form1.Controls.Add($companybox)
Any help would be greatly appreciated. I've looked around but haven't found much for v2.
Thanks.

Got it to work. I added -STA to the batch file that runs the script to change it to Single Thread Apartment.
My batch file now looks like this to run the script in STA as administrator...
SET Dir=%~dp0
SET PSPath=%Dir%Script.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-STA -NoProfile -ExecutionPolicy Bypass -File ""%PSPath%""' -Verb RunAs}";
Another option is to put this in the PS script...
if ([System.Threading.Thread]::CurrentThread.ApartmentState -eq [System.Threading.ApartmentState]::MTA)
{
powershell.exe -Sta -File $MyInvocation.MyCommand.Path
return
}
However, the second option broke the code I have to hide the console window on startup.

Related

Script to search for specific task in scheduler and delete this task

I am quite new in this area and I am bit lost but when I have looked to: https://serverfault.com/questions/604673/how-to-print-out-information-about-task-scheduler-in-powershell-script ,this was partially answering to my question. I am looking for script which will allow me to search for existing task and delete him. Problem is in version of Powershell. In my revision Get-ShceduledTask does not exists and I have to look for solution how to search like with this cmdlet. I have to note also, I cant change or upgrade Powershell to better version.
So, summarizing, the below code works at some point, but if some could help me to figure out how to accomplish this?
$sched = New-Object -Com "Schedule.Service"
$sched.Connect()
$out = #()
$sched.GetFolder("\").GetTasks(0) | % {
$xml = [xml]$_.xml
$out += New-Object psobject -Property #{
"Name" = $_.Name
"Status" = switch($_.State) {0 {"Unknown"} 1 {"Disabled"} 2 {"Queued"} 3 {"Ready"} 4 {"Running"}}
"NextRunTime" = $_.NextRunTime
"LastRunTime" = $_.LastRunTime
"LastRunResult" = $_.LastTaskResult
"Author" = $xml.Task.Principals.Principal.UserId
"Created" = $xml.Task.RegistrationInfo.Date
}
}
$out | fl Name,Status,NextRuNTime,LastRunTime,LastRunResult,Author,Created
Continuing from my comment.
They are just files on your file system.
Task Scheduler 1.0 API uses...
Get-ChildItem -Path 'C:\Windows\Tasks'
...folder to create and enumerate tasks.
Task Scheduler 2.0 API uses...
Get-ChildItem -Path 'C:\Windows\System32\Tasks'
...to create and enumerate tasks.
As well as in the registry:
Get-ChildItem -Path 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks'
Get-ChildItem -Path 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree'
Of course, using Powershell (either the version on your system or ones you can proxy to your system via PSRemoting from another system) you just pass the task name to the cmdlet. Filter as needed of course and remove the -WhatIf when you are sure you have the ones you want.
Get-ScheduledTask |
ForEach-Object {Unregister-ScheduledTask -TaskName $PSItem.TaskName -WhatIf}
Here is a function I have in my personal ModuleLibrary for this as well.
Function Get-ScheduledTasks
{
[CmdletBinding(SupportsShouldProcess)]
[Alias('gst')]
Param
(
)
schtasks.exe /query /v /fo csv |
ConvertFrom-Csv |
Where-Object { $PSItem.TaskName -ne 'TaskName' } |
Sort-Object TaskName |
Out-GridView -Title 'All scheduled tasks' -PassThru
}
Selecting from the Out-GridView will make that selection(s) available for other actions.
You could just as easily create a new function to delete them or add a switch parameter to the one above; adding this command:
schtasks.exe /delete /tn "MyTasks/Task1" /f

Get-WindowsUpdateLog stream re-direction

Has anyone noticed how the Get-WindowsUpdateLog cmdlet cannot be redirected to any streams?
Furthermore, storing the output into a variable, piping it, or any type of re-direction leads to the cmdlet to only be executed.
Any help redirecting/silencing the output of this command would be appreciated.
What I've tried:
Get-WindowsUpdateLog | Out-Null
Get-WindowsUpdateLog > $null
$sink = Get-WindowsUpdateLog
Everything I could find failed to suppress the output of the CmdLet Get-WindowsUpdateLog. As you say, the displayed information in the console is not properly following the output streams as we know them in PowerShell.
The only workaround I found is using Jobs:
$Job = Start-Job -ScriptBlock {Get-WindowsUpdateLog}
$Job | Wait-Job | Remove-Job
This way all output is handled within the job and we don't retrieve the result. It's also unnecessary to retrieve it as the result is simply a text file placed in the -Path parameter.
As an addendum to DarkLite's answer, we can also utilise the following code to check if Get-WindowsUpdateLog cmdlet worked properly :
# Generate a unique filename.
$o_filename = "C:\temp\" + "WindowsUpdateLog" + "_" + ( Get-Date -UFormat "%H_%M_%S" ) + ".txt"
$o_job = Start-Job -ScriptBlock { Get-WindowsUpdateLog -LogPath "$( $args[0] )" } `
-ArgumentList $o_filename -ErrorAction SilentlyContinue
Start-Sleep -Seconds 5
$o_job | Remove-Job -ErrorAction SilentlyContinue
if( ! ( Test-Path $o_filename ) ) {
# Return an exception
}
else {
# Do some work on the generated log file
}
I think the lesson here is don't use Out-Default in a script. https://keithga.wordpress.com/2018/04/03/out-default-considered-harmful/ I don't see that command in powershell 6. But it is in powershell 7!

Using uninstallstring through PowerShell to uninstall program

The issue I'm having right now is that when I go to run the code through PowerShell, it is changing the value of the uninstall string and adding the variable name before it. The result i'm hoping for is this.
MsiExec.exe /X{2C5B24AD-9F13-52A1-KA2N-8K4A41DC9L4G}
But the result I'm getting from the variable after replacing the /I with an /X and doing .Trim() is the following:
#{UninstallString=/X{2C5B24AD-9F13-52A1-KA2N-8K4A41DC9L4G}}
So I was wondering if you guys would be able to tell me from my code below where I'm going wrong.
I have to replace the /I with /X, because the uninstall string first comes back like this MsiExec.exe /I{2C5B24AD-9F13-52A1-KA2N-8K4A41DC9L4G}, and I'm trying to uninstall, not install.
if ($Uninstall_str) {
#run uninstall here
try {
$Uninstall_str = $Uninstall_str -replace 'MsiExec.exe /I', '/X'
$Uninstall_str = $Uninstall_str.Trim()
Start-Process "msiexec.exe" -Arg "$Uninstall_str /qb" -Wait
} catch {
Write-Output $_.Exception.Message
Write-Output $_.Exception.ItemName
Write-Warning "Error unintalling."
}
}
You didn't expand the UninstallString value when reading it from the registry. Your code for doing that probably looks somewhat like this:
$Uninstall_str = Get-ItemProperty 'HKLM:\...\Uninstall\Something' |
Select-Object UninstallString
Replace that with
$Uninstall_str = Get-ItemProperty 'HKLM:\...\Uninstall\Something' |
Select-Object -Expand UninstallString
and the problem will disappear.
To get rid of the #{uninstallstring all I needed to do was specify what I was trimming on this line
$Uninstall_str = $Uninstall_str.Trim()
So that line changed to the following to receive the results I was looking for.
$Uninstall_str = $Uninstall_str.Trim("#{UninstallString=")

Pipe all Write-Output to the same Out-File in PowerShell

As the title suggests, how do you make it so all of the Write-Outputs - no matter where they appear - automatically append to your defined log file? That way the script will be nicer to read and it removes a tiny bit of work!
Little example below, id like to see none of the "| Out-File" if possible, yet have them still output to that file!
$Author = 'Max'
$Time = Get-Date -Format "HH:mm:ss.fff"
$Title = "Illegal Software Removal"
$LogName = "Illegal_Remove_$($env:COMPUTERNAME).log"
$Log = "C:\Windows\Logs\Software" + "\" + $LogName
$RemoteLog = "\\Server\Adobe Illegal Software Removal"
Set-PSBreakpoint -Variable Time -Mode Read -Action { $global:Time = Get-Date -format "HH:mm:ss.fff" } | Out-Null
If((Test-Path $Log) -eq $False){ New-Item $Log -ItemType "File" -Force | Out-Null }
Else { $Null }
"[$Time][Startup] $Title : Created by $Author" | Out-File $Log -Append
"[$Time][Startup] Configuring initial variables required before run..." | Out-File $Log -Append
EDIT: This needs to work on PS v2.0, I don't want the output to appear on screen at all only in the log. So I have the same functionality, but the script would look like so...
"[$Time][Startup] $Title : Created by $Author"
"[$Time][Startup] Configuring initial variables required before run..."
You have two options, one is to do the redirection at the point the script is invoked e.g.:
PowerShell.exe -Command "& {c:\myscript.ps1}" > c:\myscript.log
Or you can use the Start-Transcript command to record everything (except exe output) the shell sees. After the script is done call Stop-Transcript.

Start-Transcript: This host does not support transcription

I want to start a transcript on a Windows Server 2008 R2
Start-Transcript -path C:\Temp\test.txt
"Hello!"
Stop-Transcript
But PowerShell returns the following error message:
Start-Transcript : This host does not support transcription.
How it is possible to activate transcript?
Windows PowerShell v4 ISE and lower do not support transcription. You must use the command line to run the commandlet.
From PowerShell v5 Start-Transcript is supported natively in ISE.
COMPLETE ANSWER (PowerShell ISE 2.0/4.0)::
Having yet another look at this today on another server, I noticed that the latest PowerShell ISE (which also does not allow Start-Transcript) does not have an Output pane, and instead uses the new ConsolePane. Thus the function now is as follows:
Function Start-iseTranscript
{
Param(
[string]$logname = (Get-logNameFromDate -path "C:\fso" -postfix " $(hostname)" -Create)
)
$transcriptHeader = #"
**************************************
Windows PowerShell ISE Transcript Start
Start Time: $((get-date).ToString('yyyyMMddhhmmss'))
UserName: $env:username
UserDomain: $env:USERDNSDOMAIN
ComputerName: $env:COMPUTERNAME
Windows version: $((Get-WmiObject win32_operatingsystem).version)
**************************************
Transcript started. Output file is $logname
"#
$transcriptHeader >> $logname
$psISE.CurrentPowerShellTab.Output.Text >> $logname
#Keep current Prompt
if ($Global:__promptDef -eq $null)
{
$Global:__promptDef = (gci Function:Prompt).Definition
$promptDef = (gci Function:Prompt).Definition
} else
{
$promptDef = $Global:__promptDef
}
$newPromptDef = #'
if ($Host.Version.Major -eq 2)
{
if ($Global:_LastText -ne $psISE.CurrentPowerShellTab.Output.Text)
{
Compare-Object -ReferenceObject ($Global:_LastText.Split("`n")) -DifferenceObject ($psISE.CurrentPowerShellTab.Output.Text.Split("`n"))|?{$_.SideIndicator -eq "=>"}|%{
$_.InputObject.TrimEnd()}|Out-File -FilePath ($Global:_DSTranscript) -Append
$Global:_LastText = $psISE.CurrentPowerShellTab.Output.Text
}
} elseif ($Host.Version.Major -eq 4)
{
if ($Global:_LastText -ne $psISE.CurrentPowerShellTab.ConsolePane.Text)
{
Compare-Object -ReferenceObject ($Global:_LastText.Split("`n")) -DifferenceObject ($psISE.CurrentPowerShellTab.ConsolePane.Text.Split("`n"))|?{$_.SideIndicator -eq "=>"}|%{
$_.InputObject.TrimEnd()}|Out-File -FilePath ($Global:_DSTranscript) -Append
$Global:_LastText = $psISE.CurrentPowerShellTab.ConsolePane.Text
}
}
'# + $promptDef
$Global:_LastText = $psISE.CurrentPowerShellTab.Output.Text
New-Item -Path Function: -Name "Global:Prompt" -Value ([ScriptBlock]::Create($newPromptDef)) -Force|Out-Null
}
Taking over the prompt is incredibly useful for this, however keeping two copies of the Output buffer is not ideal. I've also added in TrimEnd() as PSISE 2.0 likes to append spaces to fill the entire horizontal line width. Not sure if PSISE 4.0 does this too, but it's no problem now anyway.
NEW ANSWER (PowerShell ISE 2.0)::
I have just recently returned to this problem, and there is a way of forcing every update in PowerShell ISE to log out as a command is executed. This relies on the log path being saved in a Global Variable called _DSTranscript. This variable is passed to the Start-iseTranscript function. I have then Hijacked the Prompt function to execute a compare between _LastText and the hostUI Output Text, and append the differences out to the log. It now works a treat.
Function Start-iseTranscript
{
Param(
[string]$logname = (Get-logNameFromDate -path "C:\fso" -postfix " $(hostname)" -Create)
)
$transcriptHeader = #"
**************************************
Windows PowerShell ISE Transcript Start
Start Time: $(get-date)
UserName: $env:username
UserDomain: $env:USERDNSDOMAIN
ComputerName: $env:COMPUTERNAME
Windows version: $((Get-WmiObject win32_operatingsystem).version)
**************************************
Transcript started. Output file is $logname
"#
$transcriptHeader >> $logname
$psISE.CurrentPowerShellTab.Output.Text >> $logname
#Keep current Prompt
if ($__promptDef -eq $null)
{
$__promptDef = (gci Function:Prompt).Definition
$promptDef = (gci Function:Prompt).Definition
} else
{
$promptDef = $__promptDef
}
$newPromptDef = #'
if ($global:_LastText -ne $psISE.CurrentPowerShellTab.Output.Text)
{
Compare-Object -ReferenceObject $global:_LastText.Split("`n") -DifferenceObject $psISE.CurrentPowerShellTab.Output.Text.Split("`n")|?{$_.SideIndicator -eq "=>"}|%{ $_.InputObject.TrimEnd()}|Out-File -FilePath ($Global:_DSTranscript) -Append
$global:_LastText = $psISE.CurrentPowerShellTab.Output.Text
}
'# + $promptDef
New-Item -Path Function: -Name "Global:Prompt" -Value ([ScriptBlock]::Create($newPromptDef)) -Force|Out-Null
}
ORIGINAL ANSWER::
PowerShell ISE does not natively support Transcription. There is a Scripting Guy blog about how to achieve this. Unfortunately this needs to be the last thing that is run in the script. This means that you need to remember to run it before closing the window. I wish this worked better, or there was a way to force it to run on window closure.
This is the function that produces close to the same result as the Start-Transcript feature:
Function Start-iseTranscript
{
Param(
[string]$logname = (Get-logNameFromDate -path "C:\fso" -name "log" -Create)
)
$transcriptHeader = #"
**************************************
Windows PowerShell ISE Transcript Start
Start Time: $(get-date)
UserName: $env:username
UserDomain: $env:USERDNSDOMAIN
ComputerName: $env:COMPUTERNAME
Windows version: $((Get-WmiObject win32_operatingsystem).version)
**************************************
Transcript started. Output file is $logname
"#
$transcriptHeader >> $logname
$psISE.CurrentPowerShellTab.Output.Text >> $logname
} #end function start-iseTranscript
Either accept you can't, or use a host that does support transcripts (like the console host: PowerShell.exe).
The powershell.exe will also generate this error if there is a problem writing to the log file. For example, if the log file was created by an administrator and the user doesn't have permissions to overwrite the log.
Start-Transcript : The host is not currently transcribing.
At D:\Test1.ps1:9 char:1
+ Start-Transcript -Path "$Source\logs\Test.txt"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.StartTranscriptCommand
A good solution is to try using -Append or to make the log file unique by generating a date/time stamp.
Start-Transcript -Path "$Source\logs\Test.txt" -Append
This way a proper error message is generated.
Access to the path 'D:\Test\logs\Test.txt' is denied.
-Force has the same effect as -Append and will generate a permissions error.
Following the tip from #richard here I created a snippet that allows usage of Transaction logs where I need them (scheduled tasks), so I ended having in Windows 2008R2 the following code that can be run from powershell ISE or as a standalone script.
When run in ISE, the log information will be printed on screen
When run as a script, the log information will be saved to a file
if ($Host.Name -eq "Windows PowerShell ISE Host") {
$ISE=$true
} else {
$ISE=$false
}
if (-Not $ISE) {
$Date = Get-Date -f HHmmss_ddyyyy
Start-Transcript -Path "C:\Temp\$Date.log"
}
//////////
code here ...
//////////
if (-Not $ISE) {
Stop-Transcript
}
Tagging on to the amazing answer and work by #dwarfsoft:
if ($Host.Name -match 'ISE' -and $Host.version.Major -lt 4)
{
#Start-Transcript will not work here. Use Start-iseTranscript by #dwarfsoft above
Start-iseTranscript
}
else
{
#Start Transcript Will work here
Start-Transcript
}
In addition to the ISE (which I note the original poster LaPhi doesn't even mention), the other thing that can cause this error is if you're trying to use Start-Transcript within an Invoke-Command scriptblock. For instance if you're running the script on your client machine, and then connecting to the Windows Server 2008 R2 box via Invoke-Command so Start-Transcript outputs to the server.
When run in the local session Start-Transcript works as expected, however when using Invoke-Command the script is run within a remote session on that computer, and remote sessions have certain limitations, one of which is not supporting transcription.