Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

How to compare integer literals with another int value?

$
0
0

I want to compare a size with a threshold that will be input by the user or be set by default if no input. the threshold should be in GB, although, user shouldnt have to enter unit.

here is the code i have

param($threshold)
if(!$threshold){$threshold = 20} #threshold is GB
write-output "$threshold GB"  

Import-Module SqlServer

$Analysis_Server = New-Object Microsoft.AnalysisServices.Server  
$Analysis_Server.connect("$server")

Size = $Analysis_Server.Databases[$cube].EstimatedSize

if ($size -ge 1GB)
{
    $newSize = [pscustomobject]@{
        Size = $size/1GB; Unit = 'GB'
    }
}
elseif ($size -ge 1MB)
{
    $newSize = [pscustomobject]@{
        Size = $size/1MB; Unit = 'MB'
    }
}
elseif ($size -ge 1KB)
{
    $newSize = [pscustomobject]@{
        Size = $size/1KB; Unit = 'KB'
    }
}
else
{
    $newSize = [pscustomobject]@{
        Size = $size; Unit = 'B'
    }
}
if($newSize.Size -gt $threshold) {"exceeded the threshold!"}

the last part if($newSize.Size -gt $threshold) {"exceeded the threshold!"} doesnt work because the unit is not specified. if i use integer literal for testing purposes, i am getting the following strange output of the threshold print if i set the threshold as an integer literal like this: 20GB: 21474836480



How to update a value with two variables?

$
0
0

suppose i have the following statement

Invoke-Sqlcmd-Query"UPDATE [$Table]
SET [size] = '$newSize.Size $newSize.Unit'
WHERE [cname] = '$cube'"-ConnectionString $CS

this doesnt work and throws the following error:

Invoke-Sqlcmd : String or binary data would be truncated. The statement has been terminated.

in the table, i see this in the field:

@{Size=919.8; Unit=MB}.Size

this is because im setting two variables in one statement, but what is the proper syntax for that?

i am trying to store the following value: 919.8 MB

i tried this: '$estimatedSize.Size','$estimatedSize.Unit'

but it doesnt work either

more info related to this thread: https://stackoverflow.com/a/57531267/8397835

convert .eml to .msg

$
0
0

I have 500000 .eml files that needs to be converted to .msg file and save in local folder.

I want to know if we have any powershell command to do so?

Or any other efficient method to achieve this??(C#)

PS: Dont want to use third party converters.

DNS Zone Delegation

$
0
0

Hi folks,

i am a newbie in powershell. hope you can help me.

I must create a DNS ZONE delegation with powershell but i have no idea how i can do this.

Could some of you provide an example so then i can replace only the zones ...etc.

thanks a lot in advance

BR
Leon

Click button on web-page using power shell is not working

$
0
0

Hi Guys,

Whenever i am trying to ran the below script the new button is not working.

$url = "IE"
$ie = New-Object -com InternetExplorer.Application
$ie.visible=$True
$ie.navigate("IE")
while($ie.ReadyState -ne 4) {start-sleep -Seconds 5}
$ie.Document.getElementById('New').click()
start-sleep 5

Please help me.

Thanks in advance.

Powershell Script Automation

$
0
0

I have a script that connects to an SFTP location and synchronises a remote and Local location.  This works like a dream when i run it manually 100%.

I need to run this script every 15 mins and as such I have created a Task Scheduler Job. 

When i run the task scheduler job once created it runs but nothing happens.  

I can seem to get this job to run,  the credentials i am using are the same i created the script in and when i run manually it works it is only when i try to run the script using task scheduler it does nothing.  I am running out of ideas. 

Any assistance would be greatly appreciated.   

Look for script to install/remove programs

$
0
0

Hi,

I need to remove program1 and program2 and install program3 and program4 on multiple PCs. I will use msiexec.exe to remove the program1,2. Program3 is exe installer, program4 is MSI installer. 

Requirement: need to remove program 2 after removing program1 is completed, then install program3, when program 3 installation is completed, install program4.

I have the command line ready and tested and they worked. Can someone help to put together to create a script or point me if there is a existing script out there?

Remove program1: msiexec.exe /x {7A4192A1-84C4-4E90-A31B-B4847CA8E23A} /qn

Remove program2: msiexec.exe /x {BCF4CF24-88AB-45E1-A6E6-40C8278A70C5} /qn

Install program3: program3.exe /i "c:\"

Install proram4: msiexec.exe /a "c:\program4.exe"

Thanks in advance!


Grace

Powershell to Compare Directory File names to CSV

$
0
0

I'm no PS expert but trying to learn more to make my life easier. I will present the problem and then provide details if your interested in why this is such a pain for me right now.

Problem

I need to be able to take a list of file names (sometimes hundreds of thousands) and compare against a directory, also containing hundreds of thousands of file names, to move the matches to a seperate UPLOAD directory to isolate only the files that we want to put onto our file server.

Background

I work for a company that is in acquisition mode, we have bought so far this year 5 very large companies to incorporate into our own. We have an in house software division and an in house built CRM where we take the data from these CRM's that these companies used before and put it into our own. This includes the attachments that are the root of the problem above. The acquisitions are not slowing down and this will continue to be a painful process (takes 20 + hours as of right now to separate out the files we need from the massive file dumps we get fro these companies). I will paste the PS we have created below..feel free to criticize and tell us how terribly wrong it is. We are here to learn and get a resolution for this headache. The step that seems to be the major pain point is the COMPARE step...

#This script identifies and prepares the attachments needed to upload to our file servers
#Contents
###########################################################
#Extract - Takes a folder containing zipped folders and unzips them all to one location
#Split   - Splits out the folder of files to multiple smaller folders to improve runtime of compare step
#Compare - Compares files to CSV of files in the database and returns the files that match

#Extract
###########################################################
$ExtractRunTime = Measure-Command {
    $FolderPath = "E:\File Download\7-1-19 Download"
    $DestinationPath = "F:\DealerAttachments"

    $Files = Get-ChildItem -Path $FolderPath -Recurse -Force

    ForEach ($F in $Files.FullName) {
        Expand-Archive -Path $F -DestinationPath $DestinationPath
    }
}

$ExtractTime = "It took $([math]::Round($ExtractRunTime.Hours,2) ) hours, $([math]::Round($ExtractRunTime.Minutes,2) ) minutes, and $([math]::Round($ExtractRunTime.Seconds,2) ) seconds to unzip $($Files.Count) folders of attachments."
$ExtractTime

#Split
###########################################################
$SplitRunTime = Measure-Command {
    $FilesPerFolder = 25000 #Change this based on the number of files per folder desired
    $SourcePath = "F:\Dealer Attachments\AttachmentsSplit\1" 
    $DestPath = "F:\Dealer Attachments\AttachmentsSplit\1"
    $i = 0 #Instantiate the counting variable for the loop below. Do not change.
    $FolderNum = 1 #Instantiate the folder number variable for the loop below. Do not change.

    $GetFilesRunTime = Measure-Command {
        $Files = Get-ChildItem -Path $SourcePath -Recurse -Force
    }

    $MoveFilesRunTime = Measure-Command {
        ForEach ($F in $Files.FullName) {
            if (!(Test-Path "$DestPath\$FolderNum")) {
                    New-Item -Path "$DestPath\$FolderNum" -Type Directory -Force
                }
            Copy-Item -Path $F -Destination "$DestPath\$FolderNum"
            $i++
            if ($i -eq $FilesPerFolder){
                $FolderNum++
                $i = 0 
            }
        }
    }
}


$SplitTime = "It took $([math]::Round($SplitRunTime.Hours,2) ) hours, $([math]::Round($SplitRunTime.Minutes,2) ) minutes, and $([math]::Round($SplitRunTime.Seconds,2) ) seconds to divide the attachments into $FolderNum folders."

#Compare
###########################################################
$CSV = Import-Csv 'F:\Dealer Attachments\AttachmentsSplit\Dealer Attachments To Upload.csv'
$Destination = "F:\Dealer Attachments\AttachmentsSplit\Dealer Attachments To Upload"

$FilePath = 'F:\Dealer Attachments\AttachmentsSplit\1\1'
$Files = Get-ChildItem $FilePath

$FolderTime = Measure-Command {
    
    $CompareTime = Measure-Command {
        $Compare = Compare-Object $Files.Name $CSV.Id -IncludeEqual -ExcludeDifferent
    }

    $MoveTime = Measure-Command {
        ForEach ( $File in $Compare.InputObject ) { 
            ForEach ( $C in $CSV ) {
                If ( $File -eq $C.Id ) {
                    If ( $C.Destination -eq "OBA" ) {
                        Copy-Item ( $FilePath + '\' + $File ) $Destination
                    }
                }
            }
        }
    }
}

$OutputCompareTime = "Folder 1 took $([math]::Round($CompareTime.Hours,2) ) hours, $([math]::Round($CompareTime.Minutes,2) ) minutes, and $([math]::Round($CompareTime.Seconds,2) ) seconds to compare the files, resulting in $($Compare.Count) matches."
$OutputMoveTime = "Folder 1 took $([math]::Round($MoveTime.Hours,2) ) hours, $([math]::Round($MoveTime.Minutes,2) ) minutes, and $([math]::Round($MoveTime.Seconds,2) ) seconds to move the matching files."
$OutputFolderTime = "Folder 1 took $([math]::Round($FolderTime.Hours,2) ) hours, $([math]::Round($FolderTime.Minutes,2) ) minutes, and $([math]::Round($FolderTime.Seconds,2) ) seconds in total."

$OutputCompareTime
$OutputMoveTime
$OutputFolderTime




convert .eml to .msg

$
0
0

I have 500000 .eml files that needs to be converted to .msg file and save in local folder.

I want to know if we have any powershell command to do so?

Or any other efficient method to achieve this??(C#)

PS: Dont want to use third party converters.

WSUS Powershell Specific Update Report for list of KBs

$
0
0

Hi, I have a list of KBs and I need to get a report of number of computers that need the update corresponding to the certain KB, number of computers that have it installed or don't need it and number of computer on which the update failed.
I can get the report form the WSUS client software by going to update tabular status report, select critical and security classification (how do I specify this in script). and Any condition for the rest of the drop-downs.  The script that I am currently using is as follows:

[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") [reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer("Server01",$false);
 
$updateScope = new-object Microsoft.UpdateServices.Administration.UpdateScope;
$updateScope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::LatestRevisionApproved;
$updateScope.UpdateSources = [Microsoft.UpdateServices.Administration.UpdateSources]::MicrosoftUpdate;
 
$computerScope = new-object Microsoft.UpdateServices.Administration.ComputerTargetScope;
$updatesFailed = $updatesNeeded = $updatesUpToDate = 0;
$updates = $wsus.GetSummariesPerUpdate($updateScope, $computerScope);
$updates | foreach-object {
     if ($_.FailedCount) {
           $updatesFailed++;
     }
     elseif ($_.DownloadedCount -or $_.InstalledPendingRebootCount -or $_.NotInstalledCount) {
          $updatesNeeded++;
     }
     elseif (!$_.UnknownCount) {
          $updatesUpToDate++;
     }
}

$computersFailed = $computersNeeded = $computersUpToDate = 0;
$computers = $wsus.GetSummariesPerComputerTarget($updateScope, $computerScope);
$computers | foreach-object {
 
     if ($_.FailedCount) {
           $computersFailed++;
     }
     elseif ($_.DownloadedCount -or $_.InstalledPendingRebootCount -or $_.NotInstalledCount) {
           $computersNeeded++;
     }
     elseif (!$_.UnknownCount) {
           $computersUpToDate++;
     }
}

$wsus.ServerName+","+[DateTime]::UtcNow.ToShortDateString()+","+
$computers.Count+","+$updates.Count+","+
$computersUpToDate+","+$computersNeeded+","+$computersFailed+","+
$updatesUpToDate+","+$updatesNeeded+","+$updatesFailed;

Exception calling "ExecuteQuery" with "0" argument(s): "Root element is missing."

$
0
0

#Specify tenant admin and site URL

$User = "UserName" $ListTitle = "NewList" #Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" $Password = Read-Host -Prompt "Please enter your password" -AsSecureString #Bind to site collection $SiteURL="MySite" write-host $SiteURL $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) #Authenticate $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password) $Context.Credentials = $Creds write-host "Passed Credential Check" #Create list with "custom" list template $ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation $ListInfo.Title = $ListTitle $ListInfo.TemplateType = "100" $List = $Context.Web.Lists.Add($ListInfo) $List.Description = $ListTitle $List.Update() write-host "After $List.Update()" -foregroundcolor Green $Context.ExecuteQuery() write-host "done"

I am learning to use Powershell script.  I am attempting to create a List named "NewList" to my SharePoint Site via the above Powershell script.  I got Exception calling "ExecuteQuery" with "0" argument(s): "Root element is missing." 

On this machine, the PSVersion is 5.1.17134.858 (Windows 10)

When I run the same script on another machine with the same PS Version (Windows 10), I got the same error.  

When I run the same script on another machine with PS Version 5.1.16299.251 (Windows 10) or 4.0 (Windows Server 2012 R2).

I tried setting DNS address to 8.8.8.8 and 8.8.8.4 from this link.   It did not change anything for me. 

I tried re-installing Powershell as instructed by this link

Any idea to fix this issue on this machine? 

Thanks .

Dan Chan

When a script is run multiple times, how to append all the information in a text file, separating each run with a comment.

$
0
0

I am a newbie to powershell!

I'm trying to achieve the result that every time you execute the script, it will overwrite the previous text file. However, to put a comment at the footer of the text file.

For example

19 August 2019 19:17:20



CommandType     Name                                               ModuleName                                          
-----------     ----                                               ----------                                          
ExternalScript  TrueLayer Test.ps1                                                                                    


ASUS-G751JY xx
74336
34359738368
67108864
7x.xxx.xxx.xxx


    Directory: C:\Test


Mode                LastWriteTime     Length Name                                                                     
----                -------------     ------ ----                                                                     
d----        19/08/2019     19:15            TrueLayer                                                                


    Directory: C:\Test\TrueLayer


Mode                LastWriteTime     Length Name                                                                     
----                -------------     ------ ----                                                                     
-a---        19/08/2019     19:17        936 TLTest.txt  

Attempt1,data1, anotherdata1
Attempt2,data2, anotherdata2
Attempt3,data3, anotherdata3

I am trying to achieve the above result and i'm stuck on what script to use.

This is my script thus so far

New-Item -Path 'C:\Test\TrueLayer' -ItemType directory
#date-time
$(Get-Date) | out-file 'C:\Test\TrueLayer\TLTest.txt'

#Script Name
$MyInvocation.MyCommand | out-file 'C:\Test\TrueLayer\TLTest.txt' -Append

#user
"$env:userdomain $env:username" | out-file 'C:\Test\TrueLayer\TLTest.txt' -Append

#pid
$pid | out-file 'C:\Test\TrueLayer\TLTest.txt' -Append

#RAM
(Get-WmiObject Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum).Sum | Out-File 'C:\Test\TrueLayer\TLTest.txt'  -Append
(Get-WmiObject -class "Win32_PhysicalMemoryArray").MaxCapacity | Out-File 'C:\Test\TrueLayer\TLTest.txt' -Append

#IP
(Invoke-WebRequest -uri "http://ifconfig.me/ip").Content | Out-File 'C:\Test\TrueLayer\TLTest.txt' -Append

#List files and folders
Get-ChildItem -Recurse 'C:\Test' | Out-File 'C:\Test\TrueLayer\TLTest.txt' -Append

Function Checked-Write()
{
     [cmdletbinding()]
    Param
    (
    
         [Parameter(ValueFromPipeline,Mandatory=$true)]
         [string] $TextToWrite,
         [Parameter(Mandatory=$true, Position=1)]
         [string] $FileToWrite,
         [Parameter(Mandatory=$false,Position=2)]
         [int] $MaxWait = 10
    )

    $write_ok = $false
    do {
        try {
                # test writing to the file
                $TextToWrite | Out-File 'C:\Test\TrueLayer\TLTest.txt' -Append
                # success
                $write_ok = $true
            } catch {
             #error writing, wait a random time span
              $TimeToWait = (Get-Random -Maximum 1000)
              Start-Sleep -Milliseconds $TimeToWait
              $TimeTotal += $TimeToWait
           }
    } while (($write_ok -eq $false) -and ($TimeTotal -lt ($MaxWait * 1000)))

    return $write_ok
    
}

If anything needs to be consolidated/not required then please state. As also where i would need to put the correct cmdlet to achieve what i need everytime i execute the script.

This has been baffling me for the past 3 days

Update-Help based on date?

$
0
0

I am creating my first Powershell profile and one of the sites I was using suggested that I add Update-Help to the profile. I thought this was a good idea as well but I've noticed that every time i open the shell it will update. Despite the default of only being allowed to update once per 24 hours. I do not have the -force option on it, just Update-Help

Is there a way to only use Update-Help is this has not been done in X number of days? I have only found ways to force it update bypassing the 24 hour lockout period, but nothing to stop it from updating if it's done so already. 

YamlDotNet and powershell-yaml cmdlet gives error after conversion and unable to modify yml file as expected

$
0
0

I have main.yml file I want to append applications name My-APP to MY-APP.xml andBlue-App to Blue-App.xml

I am referring https://hochwald.net/powershell-convert-yaml-to-json-and-json-to-yaml/and executing below code, there is no error after execution but at final I am not getting $PsArray in correct .yml format

After execution it gives an error

New-Object YamlDotNet.Serialization.Serializer assembly could not loaded

I have added Add-type assembly name still not getting final .yml file with application name

change status, the error continues

Install-Module -Name powershell-yaml -Force -Repository PSGallery -Scope CurrentUser

install-package -name YamlDotNet

$RawYaml = get-content c:\temp\main.yml

# Convert YAML to PowerShell Object
$PsYaml = (ConvertFrom-Yaml -Yaml $RawYaml)

# Convert the Object to JSON
$PsJson = @($PsYaml | ConvertTo-Json)

# Convert JSON back to PowerShell Array
$PsArray = @($PsJson | ConvertFrom-Json)

# Convert the Array to YAML
ConvertTo-Yaml -Data $PsArray



main.yml file below 

--- applications: - name: MY-APP

-name: Blue-APP

settings:
  check-interval: 5s
  default-executor: jmeter

provisioning: local

How to access an expanded property as an object?

$
0
0

suppose i have the following

Function Query($Query) {
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection 
$SqlConnection.ConnectionString = "Server=$Server;Initial Catalog=$Database;Integrated Security=SSPI" 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand 
$SqlCmd.Connection = $SqlConnection 
$SqlCmd.CommandText = $Query 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$SqlAdapter.SelectCommand = $SqlCmd 
$DataSet = New-Object System.Data.DataSet 
$a=$SqlAdapter.Fill($DataSet)
$SqlConnection.Close() 
$DataSet.Tables[0] }

$PServers = Query "SELECT DISTINCT [pserver] FROM [dbo].[$Table]" | Select -ExpandProperty pserver;
$QServers = Query "SELECT DISTINCT [qserver] FROM [dbo].[$Table]" | Select -ExpandProperty qserver;

foreach($server in $PServers + $QServers)
{ 
    if($server is $PServer) {"PServer"}
    else {"QServer"}
}

How do i output the statement based on the $server type from either $PServer or $QServer?

I'd need to access $Pserver or $Qserver as an object but I cant remove expandproperty otherwise i get

System.Data.DataRow!System.Data.DataRow!System.Data.DataRow!

i tried if($server.Item(pserver)){...} and i got

error: Method invocation failed because [System.String] does not contain a method named 'Item'


Feeding data from NTUSER.DAT to PS

$
0
0

Gentlemen, 

"$Null = New-PSDrive -Name HKU -PSProvider Registry -Root HKEY_USERS"

Instead of using HKEY_USERS from my system, how can I feed data from NTUSER.DAT as the data source, collected from other machine?

Best,

Bedanta


Thanks & Regards Bedanta S Mishra

i need a PowerShell script that will remotely log into a Linux server and gather all user info

$
0
0
i am new to Powershell and recently i got a task to build a PowerShell script that will remotely log into a Linux server and gather all user info for that Linux Server and parse it into an excel sheet for a report. please help.

Getting files older than and then copying only those

$
0
0

Hi all

I am trying to list all files that have not been in use for x number of days and then copy only those files from the original folder to one set by me. 

$CutoffTime = (Get-Date).AddDays(-825)
$files = Get-ChildItem  -Recurse  -Path "folder path" | Where-Object { $_.LastAccessTime -le "$CutoffTime" } | Select-Object FullName | out-string 
foreach ($file in $files){

Copy-Item -literalpath $file -Destination "destination path"

}

i have also tried the copy job with just the -path in copy-item. 

Each time i try this solution i get the below error:

Copy-Item : Cannot find drive. A drive with the name '
O' does not exist.
At line:5 char:1
+ Copy-Item -literalpath $file -Destination (my path) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (
O:String) [Copy-Item], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.CopyItemCommand

For the life of me i cannot figure out what i am doing wrong. Also ideally i would like it to copy the folder structure. 

Thank you all kindly in advance for any assistance. 

Regards

K

Powershell - Using a powershell job within a form

$
0
0
Hi,

I am having an issue with using a Powershell job within my form. The code does not seem to run.

The "Job" button does not seem to work.

My objective is to use a job to make the form more responsive while it is gathering events and not seem to be locked up.

Thanks,

Ward.

Code follows:

function fnGet_Events($form,$DataGridView,$mode)
{
    clear
    write-host "Processing Events"
    write-host ""
    write-host "Mode: " $mode
    $dataGridView.ColumnCount = 8
    $dataGridView.ColumnHeadersVisible = $true
    $dataGridView.Columns[0].Name = "Server"
    $dataGridView.Columns[1].Name = "Log"
    $dataGridView.Columns[2].Name = "Time"
    $dataGridView.Columns[3].Name = "Type"
    $dataGridView.Columns[4].Name = "EventID"
    $dataGridView.Columns[5].Name = "Index"
    $dataGridView.Columns[6].Name = "Source"
    $dataGridView.Columns[7].Name = "Message"
    $dataGridView.Columns | Foreach-Object `
    {
        $_.AutoSizeMode = [System.Windows.Forms.DataGridViewAutoSizeColumnMode]::AllCells
    }
    $server = $env:COMPUTERNAME
    $log = "System"
    $events = Get-EventLog -LogName "System" -ComputerName "."
    $events | foreach `
    {
        # $dataGridView.Rows.Add($_.Server,$_.Log,$_.TimeGenerated,$_.EntryType,$_.EventID,$_.Index,$_.Source,$_.Message) | out-null
        $dataGridView.Rows.Add($Server,$Log,$_.TimeGenerated,$_.EntryType,$_.EventID,$_.Index,$_.Source,$_.Message) | out-null
    }
    foreach ($Row in $dataGridView.Rows)
        {
            $entry_type = $Row.Cells[3].Value
            if ($entry_type -eq 'Error')
                {
                    $row.defaultcellstyle.backcolor = "Yellow"
                }
            <#   if ($entry_type -eq 'Warning')
                {
                    $row.defaultcellstyle.backcolor = "Yellow"
                } #>
            if ($Row.Cells[0].Value -eq "")
            {
                $row.defaultcellstyle.backcolor = "Green"
            }
        }
}
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(950,810)
$form.Location = New-Object System.Drawing.Point(15,15)
$form.Text = "Event Log"
$form.StartPosition = "Manual"
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(900,700)
$dataGridView.Location = New-Object System.Drawing.Point(15,15)
$DataGridView.RowHeadersVisible = $false
$DataGridView.Anchor = 'right,bottom,top,left'
$dataGridView.AllowUserToAddRows = $false;
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Text = "Non-Job"
$Button1.Width = 147
$Button1.Height = 32
$Button1.Location = New-Object System.Drawing.Point(15,730)
$Button1.Font = "Microsoft Sans Serif,10"
$Button1.Anchor = 'bottom,left'
$Button1.Add_Click({fnGet_Events $form $DataGridView "Non-Job"})
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Text = "Job"
$Button2.Width = 147
$Button2.Height = 32
$Button2.Location = New-Object System.Drawing.Point(365,730)
$Button2.Font = "Microsoft Sans Serif,10"
$Button2.Anchor = 'bottom'
$jobScript = {fnGet_Events $form $DataGridView "Job"}
## This is where the issue is below.
$Button2.add_click({
    $ps_job = Start-Job -ScriptBlock $jobScript
    Do {[System.Windows.Forms.Application]::DoEvents()} Until ($ps_job.State -eq "Completed")
})
$Button3 = New-Object System.Windows.Forms.Button
$Button3.Text = "Exit"
$Button3.Width = 147
$Button3.Height = 32
$Button3.Location = New-Object System.Drawing.Point(766,730)
$Button3.Font = "Microsoft Sans Serif,10"
$Button3.Anchor = 'bottom,right'
$Button3.Add_Click({$form.Close()})
$form.Controls.Add($Button1)
$form.Controls.Add($Button2)
$form.Controls.Add($Button3)
$form.Controls.Add($dataGridView)
[void]$form.ShowDialog()

Remove-PSDrive not disconnecting network drives

$
0
0

I'm working on a script and the only part that doesn't work is the Remove-PSDrive command.  I've isolated each line and it's only this one not doing what I think it should.  And even when I run the command on its own it still doesn't work, nor does it give me any error

As you can see from the screen grab it's not removing the Z drive.  Am I not understanding how this command works or am I doing something wrong?

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>