I want to open a file after I select the file using the GUI. When I try my code, I can not open the file I selected. It returns Get-Content Cannot find the path. Anyone can help me, please.
Function File ($InitialDirectory)
{
Add-Type -AssemblyName System.Windows.Forms
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
If ($OpenFileDialog.ShowDialog() -eq "Cancel")
{
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
} $Global:SelectedFile = $OpenFileDialog.SafeFileName
Get-Content "$Global:SelectedFile" | ForEach-Object {
$_.Trim()
} | Where-Object {
$_ -notmatch '^(;|$)'
} | ForEach-Object {
if ($_ -match '^\[.*\]$') {
$section = $_ -replace '\[|\]'
$ini_file[$section] = #{}
} else {
$key, $value = $_ -split '\s*=\s*', 2
$ini_file[$section][$key] = $value
}
}
}
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.AutoSize = $true
$Form.text = "OpenFile"
$Form.TopMost = $true
#----------------------
$Choose1 = New-Object system.Windows.Forms.Label
$Choose1.text = "MLs"
$Choose1.AutoSize = $true
$Choose1.width = 25
$Choose1.height = 10
$Choose1.location = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor = "#000000"
$Sel = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize = $true
$Sel.width = 150
$Sel.height = 30
$Sel.location = New-Object System.Drawing.Point(120,40)
$Sel.Text = "Selected"
$Choose2 = New-Object System.Windows.Forms.Button
$Choose2.text = "Select File"
$Choose2.AutoSize = $true
$Choose2.width = 90
$Choose2.height = 20
$Choose2.location = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor = "#ffffff"
$Choose2.BackColor = "#093c76"
$Close = New-Object system.Windows.Forms.Button
$Close.BackColor = "#6996c8"
$Close.text = "Close"
$Close.width = 98
$Close.height = 30
$Close.location = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------
$Choose2.Add_Click({Sel_File
$Sel.Text = $Global:SelectedFile
})
$Form.Controls.AddRange(#($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()
My expectation, I can open the file because I want to process the file. The file that I want to open is .INI file.
Function File ($InitialDirectory)
{
Add-Type -AssemblyName System.Windows.Forms
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
If ($OpenFileDialog.ShowDialog() -eq "Cancel")
{
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
} $Global:SelectedFile = $OpenFileDialog.FileName
}
Function Get-IniContent ($Global:SelectedFile)
{
$ini = #{}
switch -regex -file $Global:SelectedFile
{
“^\[(.+)\]” # Section
{
$section = $matches[1]
$ini[$section] = #{}
$CommentCount = 0
}
“^(;.*)$” # Comment
{
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = “Comment” + $CommentCount
$ini[$section][$name] = $value
}
“(.+?)\s*=(.*)” # Key
{
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
}
}
return $ini
}
$iniContent = Get-IniContent $Global:SelectedFile
$Region = $iniContent[“Location”]
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.AutoSize = $true
$Form.text = "OpenFile"
$Form.TopMost = $true
#----------------------
$Choose1 = New-Object system.Windows.Forms.Label
$Choose1.text = "MLs"
$Choose1.AutoSize = $true
$Choose1.width = 25
$Choose1.height = 10
$Choose1.location = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor = "#000000"
$Sel = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize = $true
$Sel.width = 150
$Sel.height = 30
$Sel.location = New-Object System.Drawing.Point(120,40)
$Sel.Text = "Selected"
$Choose2 = New-Object System.Windows.Forms.Button
$Choose2.text = "Select File"
$Choose2.AutoSize = $true
$Choose2.width = 90
$Choose2.height = 20
$Choose2.location = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor = "#ffffff"
$Choose2.BackColor = "#093c76"
$Close = New-Object system.Windows.Forms.Button
$Close.BackColor = "#6996c8"
$Close.text = "Close"
$Close.width = 98
$Close.height = 30
$Close.location = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------
$Choose2.Add_Click({File
$Sel.Text = $Global:SelectedFile
})
$Form.Controls.AddRange(#($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()
I use edited code, but I can not handle the button. I want to read the INI Section [Location] after I select the file. With this code, The section already printed before I select the file.
You don't need Global variables at all for this.. Basically, the main form should capture the $Sel.Text from the dialog into a variable, check if that is not the default value of "Selected" and that should do it:
function Select-File ($InitialDirectory) {
Add-Type -AssemblyName System.Windows.Forms
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.filter = "All files (*.*)| *.*"
If ($OpenFileDialog.ShowDialog() -eq "Cancel") {
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
$result = $null
}
else {
$result = $OpenFileDialog.FileName
}
$OpenFileDialog.Dispose()
return $result
}
function Get-IniContent ($FilePath) {
$ini = #{}
switch -regex -file $FilePath
{
"^\[(.+)\]" # Section
{
$section = $matches[1]
$ini[$section] = #{}
$CommentCount = 0
}
"^(;.*)$" # Comment
{
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
}
"(.+?)\s*=(.*)" # Key
{
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
}
}
return $ini
}
###############
# Main routine
###############
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.AutoSize = $true
$Form.text = "OpenFile"
$Form.TopMost = $true
#----------------------
$Choose1 = New-Object system.Windows.Forms.Label
$Choose1.text = "MLs"
$Choose1.AutoSize = $true
$Choose1.width = 25
$Choose1.height = 10
$Choose1.location = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor = "#000000"
$Sel = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize = $true
$Sel.width = 150
$Sel.height = 30
$Sel.location = New-Object System.Drawing.Point(120,40)
$Sel.Text = "Selected"
$Choose2 = New-Object System.Windows.Forms.Button
$Choose2.text = "Select File"
$Choose2.AutoSize = $true
$Choose2.width = 90
$Choose2.height = 20
$Choose2.location = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor = "#ffffff"
$Choose2.BackColor = "#093c76"
$Choose2.Add_Click({ $Sel.Text = Select-File })
$Close = New-Object system.Windows.Forms.Button
$Close.BackColor = "#6996c8"
$Close.text = "Close"
$Close.width = 98
$Close.height = 30
$Close.location = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------
$Form.Controls.AddRange(#($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()
# if the user did not fill in anything and left the default text of "Selected", set the result to null
$selectedFile = if ($Sel.Text -ne "Selected") { $Sel.Text } else { $null }
# clean up the form
$Form.Dispose()
# here, we test if there is a file selected and if it exists
if ($selectedFile -and (Test-Path -Path $selectedFile -PathType Leaf)) {
Write-Host "Reading INI file '$($selectedFile)'"
$iniContent = Get-IniContent $selectedFile
$Region = $iniContent["Location"]
$region
}
else {
Write-Warning "The dialog was cancelled or the selected file cannot be found."
}
As per my comment, you need to change the $OpenFileDialog.SafeFileName to $OpenFileDialog.FileName.
# SafeFileName = "Config.ini"
# FileName = "\\UNC\Path\Config.ini" or "C:\Temp\Config.ini"
Function File ($InitialDirectory) {
Add-Type -AssemblyName System.Windows.Forms
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
If ($OpenFileDialog.ShowDialog() -eq "Cancel")
{
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
} $Global:SelectedFile = $OpenFileDialog.FileName
Get-Content "$Global:SelectedFile" | ForEach-Object {
$_.Trim()
} | Where-Object {
$_ -notmatch '^(;|$)'
} | ForEach-Object {
if ($_ -match '^\[.*\]$') {
$section = $_ -replace '\[|\]'
$ini_file[$section] = #{}
} else {
$key, $value = $_ -split '\s*=\s*', 2
$ini_file[$section][$key] = $value
}
}
}
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
Related
I've created this little script running in tray. I've noticed that contex menu text is not placed completely to the left. After a little investigation I found out that it is because there is a space left for .checked state indicator. I found out that it can be removed by .showcheckedmargin property of ContextMenuStrip but have no idea how to implement that.
Please advise.
add-type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'
$2 = "BASE64 CODE"
$bitmap = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap.BeginInit()
$bitmap.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($2)
$bitmap.EndInit()
$bitmap.Freeze()
$image = [System.Drawing.Bitmap][System.Drawing.Image]::FromStream($bitmap.StreamSource)
$icon = [System.Drawing.Icon]::FromHandle($image.GetHicon())
$app = New-Object System.Windows.Forms.NotifyIcon
$app.Text = ""
$app.Icon = $icon
$app.Visible = $true
$Zenek = New-Object System.Windows.Forms.MenuItem
$Zenek.Text = "Zenek"
$NetExt = New-Object System.Windows.Forms.MenuItem
$NetExt.Text = "NetExt"
$Busy = New-Object System.Windows.Forms.MenuItem
$Busy.Text = "BUSY"
$Time = New-Object System.Windows.Forms.MenuItem
$Time.Text = "Time"
$Exit = New-object System.Windows.Forms.MenuItem
$Exit.Text = "Exit"
$context = New-Object System.Windows.Forms.ContextMenu
$app.ContextMenu = $context
$app.ContextMenu.MenuItems.AddRange(#($Zenek, $NetExt, $Busy, $Time, $Exit))
$keepAwakeScript = {
while (1) {
$wsh = New-Object -ComObject WScript.Shell
$wsh.SendKeys('+{F15}')
Start-Sleep -seconds 59
}
}
Start-Job -ScriptBlock $keepAwakeScript -Name "keepAwake"|out-null
$Zenek.Add_Click({Set-Clipboard -Value "SOME TEXT"})
$NetExt.Add_Click({Set-Clipboard -Value "SOME OTHER TEXT"})
$Busy.Add_Click({
$running = Get-Job|?{$_.Name -like 'KAPS'}
$icon = new-object System.Drawing.Icon("MY PRIVATE LOCATION\red.ico")
$app.Icon = $icon
if($running -eq $null){
Start-Job -Name KAPS -ScriptBlock{
while ($true){
$shell = New-Object -ComObject WScript.Shell
$shell.SendKeys('{CAPSLOCK}')
Start-Sleep 1
}
}
}else{
Stop-Job KAPS
Remove-Job KAPS
$icon = [System.Drawing.Icon]::FromHandle($image.GetHicon())
$app.Icon = $icon
}
})
$Time.Add_Click({
$main = New-Object System.Windows.Forms.Form
$main.ClientSize = '200,200'
$main.MinimizeBox = $false
$main.MaximizeBox = $false
$label = New-Object System.Windows.Forms.Label
$label.Size = '190,30'
$label.Location = '10,10'
$label.Text = 'Ile minut?'
$font = New-Object System.Drawing.Font("Arial", 23)
$label.Font = $font
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.Size = '50,100'
$textbox.Location = '10,70'
$button = New-Object System.Windows.Forms.Button
$button.Size = '50,50'
$button.Location = '10,120'
$button.Text = 'GO'
$button.Add_Click({
$timer.Start()
$textbox.Visible =$false
$button.Visible = $false
$label.Visible = $false
$script:1 = New-TimeSpan -minutes ([int]$textbox.Text)
$label2.Visible = $true
$label2.Text = $1.ToString("mm\:ss")
})
$timer = New-Object System.Windows.Forms.Timer
$timer.Enabled = $false
$timer.Interval = '1000'
$second = New-TimeSpan -Seconds 1
$timer.Add_Tick({
$script:1 = $1.Subtract($second)
$label2.Text = $1.ToString("mm\:ss")
if($script:1.TotalSeconds -le 0){$timer.Stop(); $timer.Dispose(); [System.Windows.Forms.Application]::SetSuspendState("Hibernate", $true, $false); $main.Close(); $main.Dispose()}
})
$label2 = New-Object System.Windows.Forms.Label
$label2.Size = '190,30'
$label2.Location = '10,10'
$label2.Text = $1
$font = New-Object System.Drawing.Font("Arial", 23)
$label2.Font = $font
$label2.Visible = $false
$main.Controls.Add($textbox)
$main.Controls.Add($button)
$main.Controls.Add($label)
$main.Controls.Add($label2)
$main.ShowDialog()
})
$Exit.Add_Click({
$app.Visible = $false
Stop-Job -Name "keepAwake"
$appContext.ExitThread()
Stop-Process -Id $PID
})
$appContext = New-Object System.Windows.Forms.ApplicationContext
[void][System.Windows.Forms.Application]::Run($appContext)
For anyone with the same problem. I've managed to figure it out.
Another post from SO allowed me to do so.
I had to replace .ContextMenu with .ContextMenuStrip for the Menu itself,
replace .MenuItem with .ToolStripMenuItem, add .ShowImageMargin to ContextMenuStrip variable, then finall add items via .Items.AddRange(#()).
Before
After
In the end the code looks like this and works as intended.
add-type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'
$2 =
"BASE 64 CODE"
$bitmap = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap.BeginInit()
$bitmap.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($2)
$bitmap.EndInit()
$bitmap.Freeze()
$image = [System.Drawing.Bitmap][System.Drawing.Image]::FromStream($bitmap.StreamSource)
$icon = [System.Drawing.Icon]::FromHandle($image.GetHicon())
$app = New-Object System.Windows.Forms.NotifyIcon
$app.Text = ""
$app.Icon = $icon
$app.Visible = $true
$Zenek = New-Object System.Windows.Forms.ToolStripMenuItem
$Zenek.Text = "Zenek"
$Zenek.Checked = $true
$NetExt = New-Object System.Windows.Forms.ToolStripMenuItem
$NetExt.Text = "NetExt"
$Busy = New-Object System.Windows.Forms.ToolStripMenuItem
$Busy.Text = "BUSY"
$Time = New-Object System.Windows.Forms.ToolStripMenuItem
$Time.Text = "Time"
$Exit = New-object System.Windows.Forms.ToolStripMenuItem
$Exit.Text = "Exit"
$sep = New-Object System.Windows.Forms.ToolStripSeparator
$context = New-Object System.Windows.Forms.ContextMenuStrip
$context.ShowImageMargin = $false
$context.Items.AddRange(#($Zenek, $NetExt, $Busy, $Time, $sep, $Exit))
$app.ContextMenuStrip = $context
$keepAwakeScript = {
while (1) {
$wsh = New-Object -ComObject WScript.Shell
$wsh.SendKeys('+{F15}')
Start-Sleep -seconds 59
}
}
Start-Job -ScriptBlock $keepAwakeScript -Name "keepAwake"|out-null
$Zenek.Add_Click({Set-Clipboard -Value "SOME TEXT"})
$NetExt.Add_Click({Set-Clipboard -Value "SOME OTHER TEXT"})
$Busy.Add_Click({
$running = Get-Job|?{$_.Name -like 'KAPS'}
$icon = new-object System.Drawing.Icon("MY PRIVATE LOCATION\red.ico")
$app.Icon = $icon
if($running -eq $null){
Start-Job -Name KAPS -ScriptBlock{
while ($true){
$shell = New-Object -ComObject WScript.Shell
$shell.SendKeys('{CAPSLOCK}')
Start-Sleep 1
}
}
}else{
Stop-Job KAPS
Remove-Job KAPS
$icon = [System.Drawing.Icon]::FromHandle($image.GetHicon())
$app.Icon = $icon
}
})
$Time.Add_Click({
$main = New-Object System.Windows.Forms.Form
$main.ClientSize = '200,200'
$main.MinimizeBox = $false
$main.MaximizeBox = $false
$label = New-Object System.Windows.Forms.Label
$label.Size = '190,30'
$label.Location = '10,10'
$label.Text = 'Ile minut?'
$font = New-Object System.Drawing.Font("Arial", 23)
$label.Font = $font
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.Size = '50,100'
$textbox.Location = '10,70'
$button = New-Object System.Windows.Forms.Button
$button.Size = '50,50'
$button.Location = '10,120'
$button.Text = 'GO'
$button.Add_Click({
$timer.Start()
$textbox.Visible =$false
$button.Visible = $false
$label.Visible = $false
$script:1 = New-TimeSpan -minutes ([int]$textbox.Text)
$label2.Visible = $true
$label2.Text = $1.ToString("mm\:ss")
})
$timer = New-Object System.Windows.Forms.Timer
$timer.Enabled = $false
$timer.Interval = '1000'
$second = New-TimeSpan -Seconds 1
$timer.Add_Tick({
$script:1 = $1.Subtract($second)
$label2.Text = $1.ToString("mm\:ss")
if($script:1.TotalSeconds -le 0){$timer.Stop(); $timer.Dispose(); [System.Windows.Forms.Application]::SetSuspendState("Hibernate", $true, $false); $main.Close(); $main.Dispose()}
})
$label2 = New-Object System.Windows.Forms.Label
$label2.Size = '190,30'
$label2.Location = '10,10'
$label2.Text = $1
$font = New-Object System.Drawing.Font("Arial", 23)
$label2.Font = $font
$label2.Visible = $false
$main.Controls.Add($textbox)
$main.Controls.Add($button)
$main.Controls.Add($label)
$main.Controls.Add($label2)
$main.ShowDialog()
})
$Exit.Add_Click({
$app.Visible = $false
Stop-Job -Name "keepAwake"
$appContext.ExitThread()
#Stop-Process -Id $PID
})
$appContext = New-Object System.Windows.Forms.ApplicationContext
[void][System.Windows.Forms.Application]::Run($appContext)
I try to create a form which ask the share name, search depth and output filename and create a CSV file (which will require further processing, but this is not important now).
I have the graphical design and the script, but I cannot merge them to actually work together.
Here is the code:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Folder Group Details v1.6"
$Form.Size = New-Object System.Drawing.Size(700,400)
$Form.StartPosition = "Manual"
$Form.Location = New-Object System.Drawing.Size(90,90)
$Form.KeyPreview = $True
$Form.MaximumSize = $Form.Size
$Form.MinimumSize = $Form.Size
$Form.MinimizeBox = $True
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Font = New-Object System.Drawing.Font("Times New Roman",14,[System.Drawing.FontStyle]::Bold)
$Form.Width = $objImage.Width
$Form.Height = $objImage.Height
# Title
$Title = New-Object System.Windows.Forms.label
$Title.Location = New-Object System.Drawing.Size(150,10)
$Title.Size = New-Object System.Drawing.Size(500,70)
$Title.BackColor = "Transparent"
$Title.ForeColor = "darkblue"
$Title.Text = "Create a CSV file for the given path and depth"
$Form.Controls.Add($Title)
$Title.Font = $Font
# Start button
$Start_Button = New-Object System.Windows.Forms.Button
$Start_Button.Location = New-Object System.Drawing.Size(50,300)
$Start_Button.Size = New-Object System.Drawing.Size(100,30)
$Start_Button.Text = "Start"
$Start_Button.Font = $Font
$Start_Button.Add_Click($Button_Click)
$Form.Controls.Add($Start_Button)
#Cancel button
$Cancel_Button = New-Object System.Windows.Forms.Button
$Cancel_Button.Location = New-Object System.Drawing.Size(550,300)
$Cancel_Button.Size = New-Object System.Drawing.Size(100,30)
$Cancel_Button.Text = "Cancel"
$Cancel_Button.Font = $Font
$Cancel_Button.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$Form.Controls.Add($Cancel_Button)
$arg0_label = New-Object System.Windows.Forms.Label
$arg0_label.Location = New-Object System.Drawing.Point(50,80)
$arg0_label.Size = New-Object System.Drawing.Size(280,20)
$arg0_label.Text = 'Please enter the root of path:'
$Form.Controls.Add($arg0_label)
$arg0_textBox = New-Object System.Windows.Forms.TextBox
$arg0_textBox.Location = New-Object System.Drawing.Point(80,100)
$arg0_textBox.Size = New-Object System.Drawing.Size(250,30)
$arg0_textBox.Multiline = $False
$arg0_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg0_textBox)
$arg2_label = New-Object System.Windows.Forms.Label
$arg2_label.Location = New-Object System.Drawing.Point(50,130)
$arg2_label.Size = New-Object System.Drawing.Size(280,20)
$arg2_label.Text = 'Please enter the depth of search:'
$Form.Controls.Add($arg2_label)
$arg2_textBox = New-Object System.Windows.Forms.TextBox
$arg2_textBox.Location = New-Object System.Drawing.Point(80,150)
$arg2_textBox.Size = New-Object System.Drawing.Size(250,30)
$arg2_textBox.Multiline = $False
$arg2_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg2_textBox)
$arg1_label = New-Object System.Windows.Forms.Label
$arg1_label.Location = New-Object System.Drawing.Point(50,180)
$arg1_label.Size = New-Object System.Drawing.Size(280,20)
$arg1_label.Text = 'Please enter the output file full path and name:'
$Form.Controls.Add($arg1_label)
$arg1_textBox = New-Object System.Windows.Forms.TextBox
$arg1_textBox.Location = New-Object System.Drawing.Point(80,200)
$arg1_textBox.Size = New-Object System.Drawing.Size(250,30)
$arg1_textBox.Multiline = $False
$arg1_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg1_textBox)
#$outfile = "$arg1_textBox.Text"
# Button event
$Button_Click = {
$RootPath = $arg0_textBox.Text
$OutFile = $arg1_textBox.Text
$recurse_max = $arg2_textBox.Text
$recurse_current = 0
$Header = "Folder Path,IdentityReference,FileSystemRights,IsInherited"
Remove-Item $OutFile
Add-Content -Value $Header -Path $OutFile
function print_acl
{
$RootPath = $arg0_textBox.Text
$recurse_current = $arg1_textBox.Text
Write-Host "$RootPath : $recurse_current"
if ($RootPath -ne "" -and $null -ne $RootPath ) {
$ACLs = get-acl $RootPath | ForEach-Object { $_.Access }
Foreach ($ACL in $ACLs){
$rights = $ACL.FileSystemRights -replace ", ", ":"
$OutInfo = $RootPath + "," + $ACL.IdentityReference + "," + $rights + "," + $ACL.IsInherited
Add-Content -Value $OutInfo -Path $OutFile
}
if ($recurse_current -lt $recurse_max) {
$Folders = Get-ChildItem $RootPath | Where-Object {$_.psiscontainer -eq $true}
foreach ($Folder in $Folders){
$recurse_current = $arg1_textBox.Text + 1
print_acl $Folder.Fullname $recurse_current
}
}
}
}
print_acl $RootPath $recurse_current
}
$Form.Topmost = $True
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
The problem is I don't understand why the Start button don't do anything.
What do I do wrong?
I'm a very beginner in this field so sorry for being so lame.
Thank you.
There's no need to make your own recursive function for Get-ChildItem - it has a -Depth Parameter
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Folder Group Details v1.6"
$Form.Size = '700,400'
$Form.StartPosition = "Manual"
$Form.Location = '90,90'
$Form.KeyPreview = $True
$Form.MaximumSize = $Form.Size
$Form.MinimumSize = $Form.Size
$Form.MinimizeBox = $True
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Font = New-Object System.Drawing.Font("Times New Roman",14,[System.Drawing.FontStyle]::Bold)
$Form.Width = $objImage.Width
$Form.Height = $objImage.Height
# Title
$Title = New-Object System.Windows.Forms.label
$Title.Location = '150,10'
$Title.Size = '500,70'
$Title.BackColor = "Transparent"
$Title.ForeColor = "darkblue"
$Title.Text = "Create a CSV file for the given path and depth"
$Form.Controls.Add($Title)
$Title.Font = $Font
# Start button
$Start_Button = New-Object System.Windows.Forms.Button
$Start_Button.Location = '50,300'
$Start_Button.Size = '100,30'
$Start_Button.Text = "Start"
$Start_Button.Font = $Font
$Start_Button.Add_Click($Button_Click)
$Form.Controls.Add($Start_Button)
#Cancel button
$Cancel_Button = New-Object System.Windows.Forms.Button
$Cancel_Button.Location = '550,300'
$Cancel_Button.Size = '100,30'
$Cancel_Button.Text = "Cancel"
$Cancel_Button.Font = $Font
$Cancel_Button.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$Form.Controls.Add($Cancel_Button)
$arg0_label = New-Object System.Windows.Forms.Label
$arg0_label.Location = '50,80'
$arg0_label.Size = '280,20'
$arg0_label.Text = 'Please enter the root of path:'
$Form.Controls.Add($arg0_label)
$arg0_textBox = New-Object System.Windows.Forms.TextBox
$arg0_textBox.Location = '80,100'
$arg0_textBox.Size = '250,30'
$arg0_textBox.Multiline = $False
$arg0_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg0_textBox)
$arg2_label = New-Object System.Windows.Forms.Label
$arg2_label.Location = '50,130'
$arg2_label.Size = '280,20'
$arg2_label.Text = 'Please enter the depth of search:'
$Form.Controls.Add($arg2_label)
$arg2_textBox = New-Object System.Windows.Forms.TextBox
$arg2_textBox.Location = '80,150'
$arg2_textBox.Size = '250,30'
$arg2_textBox.Multiline = $False
$arg2_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg2_textBox)
$arg1_label = New-Object System.Windows.Forms.Label
$arg1_label.Location = '50,180'
$arg1_label.Size = '280,20'
$arg1_label.Text = 'Please enter the output file full path and name:'
$Form.Controls.Add($arg1_label)
$arg1_textBox = New-Object System.Windows.Forms.TextBox
$arg1_textBox.Location = '80,200'
$arg1_textBox.Size = '250,30'
$arg1_textBox.Multiline = $False
$arg1_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg1_textBox)
# Button event
$Button_Click = {
$RootPath = $arg0_textBox.Text
$OutFile = $arg1_textBox.Text
$recurse_max = $arg2_textBox.Text
$Results = Get-ChildItem -Path $RootPath -Depth $recurse_max | Where-Object {$_.psiscontainer -eq $true} | ForEach-Object {
$FileDetail = $_
$ACLs = get-acl $_.FullName | ForEach-Object { $_.Access }
$ACLs | ForEach-Object {
$rights = $_.FileSystemRights -replace ", ", ":"
[pscustomobject]#{Folder=$FileDetail.Name;Path=$FileDetail.FullName;IdentityReference=$_.IdentityReference;FileSystemRights=$rights;IsInherited=$_.IsInherited}
}
}
$Results | Export-Csv -Path $OutFile -NoTypeInformation
}
$Form.Topmost = $True
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
I am trying to make a New-ScheduledJob to run a PowerShell script that checks for an app and pops up a notification GUI when a user logs in if it finds the app. This worked fine using New-ScheduledTask, but I am having trouble getting New-ScheduledJob to function the same way. Specifically with the credentials bit and making sure there is no password prompt when the script runs, here's how I did it using the New-ScheduledTask cmdlet.
The specific issues I am facing are
I was able to run the task with the code below as the service account, and haven't found a method to do this with the scheduledjobs cmdlets.
when I create the new scheduledjob via the script it does not pop the form that it should. I believe it is running in the background but do not know how to correct this.
I will include first the working script that was used with the schedulenewtask cmdlet and then the new script I have been thus far unsuccessful with.
$A = New-ScheduledTaskAction -Execute "office_check_funct_test.ps1" -WorkingDirectory "C:\Users\user\Desktop\notify"
$T = New-ScheduledTaskTrigger -AtLogOn
$S = New-ScheduledTaskSettingsSet -StartWhenAvailable
$P = New-ScheduledTaskPrincipal -UserId "LOCALSERVICE" -LogonType ServiceAccount
$D = New-ScheduledTask -Principal $P -Action $A -Trigger $T -Settings $S
function Check_Program_Installed($programName) {
$x86_check = ((Get-ChildItem "C:\Program Files (x86)\Microsoft Office") |
Where-Object { $_."Name" -like "*$programName*" }).Length -gt 0;
if (Test-Path 'C:\Program Files (x86)\Microsoft Office') {
$x64_check = ((Get-ChildItem "C:\Program Files (x86)\Microsoft Office") |
Where-Object { $_."Name" -like "*$programName*" }).Length -gt 0;
}
return $x86_check -or $x64_check;
}
$check = Check_Program_Installed("Office12")
if ($check -eq $false) {
try {
Register-ScheduledTask -InputObject $D -TaskName T1 -ErrorAction SilentlyContinue
} catch {
}
Enable-ScheduledTask -TaskName T1 -ErrorAction SilentlyContinue
Add-Type -AssemblyName System.Windows.Forms
$config = '.\config.txt'
$values = Get-Content $config | Out-String | ConvertFrom-StringData
$values.textAlign
# hashtable, hence this variable
$values1 = Get-Content $config
$values1[3]
$res = (Get-WmiObject -Class Win32_VideoController).VideoModeDescription -split " x "
$displayWidth = $res[0]
$displayHeight = $res[1]
$formWidth = $values.formWidth
$formHeight = $values.formHeight
$bufferWidth = $values.bufferWidth
$bufferHeight = $values.bufferHeight
$locX = $displayWidth - $formWidth - $bufferWidth
$locY = $displayHeight - $formHeight - $bufferHeight
$image = [system.Drawing.Image]::FromFile('.\logo.png')
$form = New-Object System.Windows.Forms.Form
$form.StartPosition = 'Manual'
$form.ClientSize = "$($formWidth),$($formHeight)"
$form.Location = "$($locX),$($locY)"
$form.FormBorderStyle = 'FixedDialog'
$form.MinimizeBox = $false
$form.MaximizeBox = $false
$form.BackgroundImage = $image
$form.BackgroundImageLayout = 'None'
$form.BackColor = $values.formBackColor
$form.Opacity = $values.formOpacity
$button1 = New-Object System.Windows.Forms.Button
$button1.Visible = $true
$button1Width = $values.button1Width
$button1Height = $values.button1Height
$button1.DialogResult = 'OK'
$button1.Size = "$($button1Width),$($button1Height)"
$button1.Font = $values.buttonFont
$button1.Text = $values.buttonText
$buttonLocX = $values.buttonLocX
$buttonLocY = $values.buttonLocY
$button1.Location = "$($buttonLocX),$($buttonLocY)"
$button1.BackColor = $values.buttonBackColor
$button1.ForeColor = $values.buttonForeColor
$text = Get-Content -PSPath '.\message.txt'
$lableLocX = $values.textBoxLocX
$lableLocY = $values.textBoxLocY
$label2 = New-Object System.Windows.Forms.Label
$label2.Text = $text
$label2.Font = $values.font
$label2.Size = $values.textBoxSize
$label2.Location = "$($lableLocX),$($lableLocY)"
$label2.BackColor = $values.textBoxBackColor
$label2.ForeColor = $values.textColor
$label2.TextAlign = $values1[3] -split 'textAlign= ' | Out-String
$Icon = [system.drawing.icon]::ExtractAssociatedIcon(".\star_logo.ico")
$form.Icon = $Icon
$form.Controls.AddRange(#($button1, $label2))
[void]$form.ShowDialog()
} elseif ($check -eq $true) {
Disable-ScheduledTask -TaskName T1
}
function Check_Program_Installed($programName) {
$x86_check = ((Get-ChildItem -ErrorAction SilentlyContinue "C:\Program Files (x86)\Microsoft Office\Office12") |
Where-Object { $_."Name" -like "*$programName*" }).Length -gt 0;
if (Test-Path -ErrorAction SilentlyContinue 'C:\Program Files (x86)\Microsoft Office\Office12') {
$x64_check = ((Get-ChildItem -ErrorAction SilentlyContinue "C:\Program Files (x86)\Microsoft Office\Office12") |
Where-Object -ErrorAction SilentlyContinue { $_."Name" -like "*$programName*" }).Length -gt 0;
}
return $x86_check -or $x64_check;
}
$check = Check_Program_Installed("excel")
if ($check -eq $false) {
try {
$S = New-ScheduledJobOption -RunElevated -ContinueIfGoingOnBattery
$logon = New-JobTrigger -AtLogOn
$account = New-Object System.Management.Automation.PSCredential "domain/user"
Register-ScheduledJob -ErrorAction SilentlyContinue -FilePath C:\doucments\scripts\test_job.ps1 -argument form -Name TestJob4 -ScheduledJobOption $S -Trigger $logon -Credential $account
} catch {
}
try {
Enable-ScheduledJob -ErrorAction SilentlyContinue -Name TestJob1
} catch {
}
Add-Type -AssemblyName System.Windows.Forms
$config = '.\config.txt'
$values = Get-Content $config | Out-String | ConvertFrom-StringData
$values.textAlign
$values1 = Get-Content $config
$values1[3]
$res = (Get-WmiObject -Class Win32_VideoController).VideoModeDescription -split " x "
$displayWidth = $res[0]
$displayHeight = $res[1]
$formWidth = $values.formWidth
$formHeight = $values.formHeight
$bufferWidth = $values.bufferWidth
$bufferHeight = $values.bufferHeight
$locX = $displayWidth - $formWidth - $bufferWidth
$locY = $displayHeight - $formHeight - $bufferHeight
$image = [system.Drawing.Image]::FromFile('.\logo.png')
$form = New-Object System.Windows.Forms.Form
$form.StartPosition = 'Manual'
$form.ClientSize = "$($formWidth),$($formHeight)"
$form.Location = "$($locX),$($locY)"
$form.FormBorderStyle = 'FixedDialog'
$form.MinimizeBox = $false
$form.MaximizeBox = $false
$form.BackgroundImage = $image
$form.BackgroundImageLayout = 'None'
$form.BackColor = $values.formBackColor
$form.Opacity = $values.formOpacity
$button1 = New-Object System.Windows.Forms.Button
$button1.Visible = $true
$button1Width = $values.button1Width
$button1Height = $values.button1Height
$button1.DialogResult = 'OK'
$button1.Size = "$($button1Width),$($button1Height)"
$button1.Font = $values.buttonFont
$button1.Text = $values.buttonText
$buttonLocX = $values.buttonLocX
$buttonLocY = $values.buttonLocY
$button1.Location = "$($buttonLocX),$($buttonLocY)"
$button1.BackColor = $values.buttonBackColor
$button1.ForeColor = $values.buttonForeColor
$text = Get-Content -PSPath '.\message.txt'
$lableLocX = $values.textBoxLocX
$lableLocY = $values.textBoxLocY
$label2 = New-Object System.Windows.Forms.Label
$label2.Text = $text
$label2.Font = $values.font
$label2.Size = $values.textBoxSize
$label2.Location = "$($lableLocX),$($lableLocY)"
$label2.BackColor = $values.textBoxBackColor
$label2.ForeColor = $values.textColor
$label2.TextAlign = $values1[3] -split 'textAlign= ' | Out-String
$Icon = [system.drawing.icon]::ExtractAssociatedIcon(".\star_logo.ico")
$form.Icon = $Icon
$form.Controls.AddRange(#($button1, $label2))
[void]$form.ShowDialog()
} elseif ($check -eq $true) {
Disable-ScheduledJob -Name TestJob3
}
I got a script which is handling some things. I know a lot say I should get more short scripts which are working. But there are many people which can't handle many files or scripts and want 1 which can do all, and I can't tell 600 people which script does what. I need a kind of assembling at least of a few.
I wanted to make a workaround for the canceld options. The easiest way is to wrap all the code in a do {} while () for sure. But are there any options where I can repeat a single option? Something like when it asks do you really want to cancel.
And a real annoying bug I can't fix is that after every single action the start form blops up again. I tried out diffrent ways to debug with a counter but it didn't count up and also I tried to put the function assembling at a other place didn't fix it as well. Don't know why it happens.
Code for repro
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Set-PSDebug -Strict #Errorcall if a variable isnt declared
#Function Assembling
function Saveat()
{
#working
$Saveat = New-Object -Typename System.Windows.Forms.SaveFileDialog
$Saveat.filter = "CSV (*.csv)| *.csv"
#IF selection is canceld
$result = $form.ShowDialog()
[void]$Saveat.ShowDialog()
return $Saveat.FileName
}
function Compare($location1, $location2)
{
#work in progress
$CSV1 = Import-Csv -Path $location1 -UseCulture
$CSV2 = Import-Csv -Path $location2 -UseCulture
$Compared = Compare-Object -ReferenceObject $CSV1 -DifferenceObject $CSV2 |
select -ExpandProperty inputObject |
sort
[void] $CSV1
[void] $CSV2
return $Compared
}
function whichcsv()
{
#working
$location = New-Object System.Windows.Forms.OpenFileDialog
$location.Filter = "CSV (*.csv)| *.csv"
$result = $form.ShowDialog()
[void]$location.ShowDialog()
return $location.FileName
}
#Select which option Form
#region Initiate Form **This Form Blops up after every user action**
$form = New-Object System.Windows.Forms.Form
$form.Text = "CSV Liste"
$form.Size = New-Object System.Drawing.Size(300,300)
$form.StartPosition = "CenterScreen"
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,195)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,195)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Welche CSV Liste soll geladen werden:"
$form.Controls.Add($label)
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 150
[void] $listBox.Items.Add("List Filter")
[void] $listBox.Items.Add("ADComputer")
[void] $listBox.Items.Add("AS400 Personal Not implemented yet")
[void] $listBox.Items.Add("ADBenutzer Not implemented yet")
#endregion
$form.Controls.Add($listBox)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
#Choosed Option
$x = $listBox.SelectedItem
switch ($x)
{
#Option 1 working
"List Filter"
{
#Select path of the CSV
$csvpath = whichcsv
#IF selection is canceld
if ($csvpath -eq "")
{
Write-Host "Operation Canceld"
}
else
{
#CSV Import and Filter set
$CSV = Import-Csv -Path $csvpath -UseCulture
$Filter = Read-Host "Please enter columname. Leave clear for cancel"
if ($Filter -eq "")
{
Write-Host "Operation canceld"
}
else
{
$y = $CSV | Select $Filter
Write-Host "CSV Successfull Imported and Filter set"
}
$SDestination = Saveat
if ($SDestination -eq "")
{
Write-Host "Operation Canceld"
}
else
{
Write-Host "Process started"
foreach ($y1 in $y)
{
New-Object PSObject -Property #{Inventarnummer=$y1.$Filter} | Export-Csv $SDestination -NoTypeInformation -Append
}
Write-Host "Process finished"
}
}
}
#Option 2 working
"ADComputer"
{
#Select path of the CSV
$csvpath = whichcsv
#IF selection is canceld
if ($csvpath -eq "")
{
Write-Host "Operation Canceld"
}
else
{
#CSV Import with filter
$CSV = Import-Csv -Path $csvpath -Delimiter ','
$Filter = Read-Host "Please enter columname. Leave clear for cancel"
if ($Filter -eq "")
{
Write-Host "Operation canceld"
}
else
{
$y = $CSV | Select $Filter
Write-Host "CSV Successfull Imported and Filter set"
}
#Path selection
$Saveworking = Saveat
$SaveFailed = Saveat
if($Saveworking -eq "")
{
Write-Host "Operation canceld"
}
elseif ($SaveFailed -eq "")
{
Write-Host "Operation canceld"
}
else
{
#Progress
Write-Host "Process Start"
foreach($n in $y)
{
try
{
$Computer = [system.net.dns]::resolve($n.$Filter) | Select HostName,AddressList
$IP = ($Computer.AddressList).IPAddressToString
Write-Host $n.$Filter $IP
New-Object PSObject -Property #{IPAddress=$IP; Name=$n.$Filter} | Export-Csv $Saveworking -NoTypeInformation -Append
}
catch
{
Write-Host "$($n.$Filter) is unreachable."
New-Object PSObject -Property #{Name=$n.$Filter} | Export-Csv $SaveFailed -NoTypeInformation -Append
}
}
Write-Host "Process successfull completed"
}
}
}
#Option 3 Not implemented yet
"AS400 Personal Not implemented yet"
{
Write-Host "Not implemented yet"
}
#Option 4 not implemented yet
"ADBenutzer Not implemented yet"
{
Write-Host "Not implemented yet"
}
}
}
else
{
Write-Host "Operation Canceld"
}
I guess you need to work with form events rather than .DialogResult.
For the Cancel button you would probably do something like: $CancelButton.Add_Click({[Void]$Form.Window.Close()})
For the OK button you would probably want to put the majority of your OK task in a function and invoke it from a similar event:
Function Task {
#Choosed Option
$x = $listBox.SelectedItem
switch ($x)
{
#Option 1 working
"List Filter"
{
#Select path of the CSV
$csvpath = whichcsv
...
$OkButton.Add_Click({Task})
(And close the dialog ([Void]$Form.Window.Close()) when the task is completed)
Looking to change yyyy,MM,dd to user input date. Similarly looking to change abcd,ef,gh also to user input date. abcd,ef,gh gets succesfully converted to the date user inputs. However, yyyy,MM,dd stays the same.
Here is the data in the output text file:
(Global History"&customer=guest&password=guest&STARTTIME=yyyy,MM,dd,00,00,00&STOPTIME=abcd,ef,gh,00,00,00&POINTSEVERY=15 min&GRAPHTYPE=excel)
Here is the script:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object Windows.Forms.Form
$form.Text = "Select a From Date"
$form.Size = New-Object Drawing.Size #(243,230)
$form.StartPosition = "CenterScreen"
$calendar = New-Object System.Windows.Forms.MonthCalendar
$calendar.ShowTodayCircle = $False
$calendar.MaxSelectionCount = 1
$form.Controls.Add($calendar)
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(38,165)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(113,165)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$form.Topmost = $True
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
Remove-Item H:\oim\adcbsm007\karthik.txt
$path = "H:\oim\adcbsm007\adcbsm007.txt"
$word1 = "yyyy,MM,dd"
$replacement = $calendar.SelectionStart
$text1 = Get-Content $path
$newText = $text -replace $word, $replacement.ToString('yyyy,MM,dd')
$newText > "H:\oim\adcbsm007\karthik.txt"
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
$path = "H:\oim\adcbsm007\adcbsm007.txt"
$word = "abcd,ef,gh"
$replacement2 = $calendar.SelectionStart
$text = Get-Content $path
$newText = $text2 -replace $word, $replacement.ToString('yyyy,MM,dd')
$newText > "H:\oim\adcbsm007\karthik.txt"
}
}
You initialize the variables $word1 and $text1, but then you try to replace $word in $text:
$word1 = "yyyy,MM,dd"
$replacement = $calendar.SelectionStart
$text1 = Get-Content $path
$newText = $text -replace $word, $replacement.ToString('yyyy,MM,dd')
Replace the line
$newText = $text -replace $word, $replacement.ToString('yyyy,MM,dd')
with
$newText = $text1 -replace $word1, $replacement.ToString('yyyy,MM,dd')
and the code should do what you expect.