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

Script to find on which servers an account is logged into

$
0
0
Anyone has any script to find out on which servers a useraccount is logged on to. I want to logoff the session from all servers, before changing password to prevent account lockout later.

Issue when retrieving ADUser Object remotely

$
0
0

Hi,

I have an issue in these lines :

Invoke-Command -Session $ADSession -ScriptBlock{
    param(
      [Parameter(Mandatory, Position = 0)]
      [string]$UserUPN
    )
    $ADUser = Get-ADUser -Filter "UserPrincipalName -like '$UserUPN'" -SearchScope Subtree
   } -ArgumentList $UserUPN 

If I type the Get-ADUser interactively in the session and stores it in a variable, I have what I expected : An ADUser object. But if I do the same remotely, the result is a string containing the CN.

Do you have any idea ?


The key of learning is practice.


Retrieving both direct and indirect group members for a user

$
0
0

Hello all,

I have created a script to find only the indirect group members. Unfortunately the array $arrOnlyIndirectMembers shows some members that are also a part of aray $arrOnlyDirectMembers. So there is something wrong, but I do not what exactly.

   Clear-Host
   #Show direct and indirect members
   $username = "willem-janrw10"

   $dn = (Get-ADUser $username).DistinguishedName

   $arrDirectAndIndirectMembers = Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn)     | Select-Object Name | Sort-Object -Property Name
   $arrOnlyDirectMembers        = Get-ADPrincipalGroupMembership $username                                     | Select-Object Name | Sort-Object -Property Name
   $arrOnlyIndirectMembers      = Compare-Object $arrOnlyDirectMembers $arrDirectAndIndirectMembers -PassThru  | Select-Object Name | Sort-Object -Property Name
   Write-Host "--- DIRECT AND INDIRECT MEMBERSHIP ---"
   ForEach($objItem in $arrDirectAndIndirectMembers)
   {
   Write-Host $objItem.Name
   }

   Write-Host "--- DIRECT MEMBERSHIP ---"
   ForEach($objItem in $arrOnlyDirectMembers)
   {
   Write-Host $objItem.Name
   }

   Write-Host "--- ONLY INDIRECT ---"
   ForEach($objItem in $arrOnlyIndirectMembers)
   {
   Write-Host $objItem.Name
   }

So my question is: what I am doing wrong? Any help is appreciated.

With kind regards,

Willem-Jan

powershell Exchange command with subject before

$
0
0

Hello,

I would like to execute a command in Exchange powershell. 

The command is:

[foreach ($mail in (Get-Content 'C:\temp\UserID.txt')) {Add-Content 'c:\temp\mailboxes.txt'-value $mail ; get-mailboxFolderStatistics -Identity domain\$mail | select Name,FolderSize,FolderAndSubfolderSize,ItemsInFolder}

The command get User IDs from the txt file and put the ID in $mail. After then the command will be execute. I only want to get the output from the command in a textfile starting with the current value of the $mail. Is that possible?

AD Computer Registry Search

$
0
0

Hi,

I'm trying to search the registry of all the computers in my domain for a specific string and return the values in a CSV file with "Computer Name" & "Serial." with the following and can't seem to get it working:

get-adcomputer | select dnshostname | get-ItemProperty -path HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PKWARE\SN\0x9E0 -name"serial"
out-File serial.csv -append

Any help works

ty

Michael

DSC for .NET 4.7.2 install

$
0
0

Hello/Help

do i need a product id? 

this is what i have

@{
                ShortName       = "NETFramework472"
                Name            = "Microsoft .NET Framework 4.7.2"
                Path            = "\\serverlocation\files\Apps\Config\Package\NDP472-KB4054530-x86-x64-AllOS-ENU.exe"
                ProductId       = "09CCBE8E-C964-30EF-AE84-6537AC4197F9"
Role           =  "Apps' #Install on App Role Only
                Arguments       = "/q /norestart"
            }


How to use PsPing as job

$
0
0

I want to use infinite loop PsPing as job.

But I got error  ( -t option is not supported when using input redirection, )

How to solve this problem??

Here is my code

Start-Job{
    psping -t -t -w 0 <serverIp:port> `
            | % { $result=("{0} - {1}" -f (Get-Date), $_) `
                    | Select-String connecting;
                   if ($result -ne $null) {
                     $result
                   }
                }
}




Deploy Printer via PowerShell for Microsoft Intune

$
0
0

Hi all,

I'm trying to install a printer driver for our Canon 7260/7270i printer in the office on a Windows 10 Enterprise laptop. I used the script below which fails:

Add-PrinterDriver : The specified driver does not exist in the driver store.
At C:\Users\intune_Saa\AppData\Local\Temp\RarSFX0\Deploy-Printer.ps1:267 char:5+     Add-PrinterDriver -Name $PrinterDriver+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : NotSpecified: (MSFT_PrinterDriver:ROOT/StandardCimv2/MSFT_PrinterDriver) [Add-PrinterDri   ver], CimException    + FullyQualifiedErrorId : HRESULT 0x80070705,Add-PrinterDriver

Add-Printer : The specified driver does not exist.  Use add-printerdriver to add a new driver, or specify an existing
driver.
At C:\Users\intune_Saa\AppData\Local\Temp\RarSFX0\Deploy-Printer.ps1:281 char:5+     Add-Printer -Name $PrinterName -PortName $PrinterPortName -Driver ...+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : NotSpecified: (MSFT_Printer:ROOT/StandardCimv2/MSFT_Printer) [Add-Printer], CimException    + FullyQualifiedErrorId : HRESULT 0x80070705,Add-Printer

I cannot find out how to add the driver to the driver store. Can someone help me out here? I used the latest PCL6 Generic driver from the cannot website and I used this script https://gallery.technet.microsoft.com/Deploy-Printer-via-d557b5ad where I filled in the variables and followed the rest of the instructions outlined:

#########################
#    PowerShell Help    #
#########################<#
.SYNOPSIS    This script is designed to deploy printers to Windows 10 workstations deployed and triggered by Intune.
.DESCRIPTION    Written by Jean-Pierre Simonis, Delivery Quality Assurance    https://www.linkedin.com/in/jsimonis/    Version 1.1    #########################    #      Change Log       #    #########################        # 23/11/2017 1.1    # Features    # - Add support for MSI install keys so that script deployment via Intune reports as successful    #    # 10/11/2017 v1.0 - Initial Release    #  Features    # - Error trapping and logging     # - Unzip Printer Driver package    # - Install Local Printer Queue   
.NOTES    #########################    #         Notes         #    #########################    # This script is designed to be packaged as an exe and pushed out via Intune    #    #    # This script requires the following permissions    #     #  - Elevated PowerShell Session first time only to create custom eventlog type    #  - Permission to update install the printer (Assumed it will run in Intune installation context)    #  - Your endpoint protection may need this package to be added as an exception as it might detect and block it as this script extracts itself and launch a script in an administrative context    # Installation    # 1. Ensure script is run against Windows 10 devices with at least PowerShell V5.1    # 2. Create printer driver zip file    # 3. Configure variables in PowerShell Script to desired printer configuration supply name of driver zip file    # 4. Create batch file to launch PowerShell script (Refer below instructions for contents of batch file)    # 5. Create Self-extracting executable (I used WinRAR)     #       a. Configure it to extract to temporary directory    #       b. Configure post launch a command (deploy.bat)    #       c. Configure Icon, Overwrite (Replace) and Title settings    #       d. Configure for silent extraction (hidden dialogs)    #       e.  Ensure deploy.bat, Deploy-Printer.ps1, PrinterDriver.zip are added to archive    # 6. Use MSI Wrapper to convert the EXE to MSI    #       a. download from http://www.exemsi.com    #       b. Configure MSI Settings    #              Application ID (ensure this value is the same as defined in script configuration)    #              Deploy Printer Package 1    #              Upgrade Code (This can generated by MSI Wrapper)    #              {E6454CC0-00B2-4134-9D28-9089E5628C4B}    #              Product Name    #              Deploy Printer Package    #              Version    #              1.0.0.0    #              Icon    #              PowerShell.ico (I downloaded and used a powershell logo in ico format)    #              Comments    #              PowerShell Script to Deploy Campus Side Printer    #    # 7. (Optional) Use ORCA to modify MSI tables to update product name to remove (wrapped by MSI Wrapper in title or buy the product)    #        a. download from https://msdn.microsoft.com/en-us/library/windows/desktop/aa370557(v=vs.85).aspx    # 8. Configure Intune to deploy LOB Windows Application    # 9. Enjoy Customer Success 😊
    # Contents of deploy.bat    @echo off    REM Written by Jean-Pierre Simonis, Delivery Quality Assurance, www.deliveryqa.com.au     @echo Launching Printer Deployment PowerShell Script    powershell.exe -executionpolicy unrestricted -file .\Deploy-Printer.ps1    # End of Script
.LINK
http://www.deliveryqa.com.au
#>
#########################
#   Pre-req Functions   #
#########################
#Function to log to file and write output to host
#Logging can be configured through the logging section in the Configuration area of this script.
Function LogWrite
{    Param (    [Parameter(Mandatory=$True)]    [string]$Logstring,    [Parameter(Mandatory=$True)]    [string]$type,    [Parameter(Mandatory=$False)]    [string]$v        )    #Check if Logging is wanted    if ($global:logging -eq $true) {                #Determine Log Entry Type               Switch ($type){            start {                 $logType = "[Start]"                $elogtype = "Information"                $logColour = "Green"            }            i {                 $logType = "[Info]"                $elogtype = "Information"                $logColour = "White"            }            w {                 $logType = "[Warning]"                $elogtype = "Warning"                $logColour = "Yellow"            }            e {                 $logType = "[Error]"                $elogtype = "Error"                $logColour = "Red"            }            end {                 $logType = "[End]"                $elogtype = "Information"                $logColour = "Green"            }        }        #Log Time Date for each log entry        if ($global:logTimeDate -eq $true) {            $TimeStamp = Get-Date -Format "yyyy-MM-dd-HH:mm"            $TimeStamp = "[$TimeStamp]"        } else {            $TimeStamp = $Null        }        #Create Eventlog Source        if ($global:logtoEventlog -eq $true) {            #Check if log source exists            $checkLogSourceExists = [System.Diagnostics.EventLog]::SourceExists("$global:eventlogSource")            if ($checkLogSourceExists -eq $False) {                New-EventLog -LogName Application -Source $global:eventlogSource -ErrorAction SilentlyContinue            }        }        #Check if Verbose logging enabled and of log entry is marked as verbose        if ($global:verboselog -eq $true -and $v -eq $true){            #Check if Log Entry is marked as verbose                      if ($global:logtoFile -eq $true) {Add-Content $Logfile -value "$TimeStamp[Verbose]$logType $logstring" -ErrorAction Stop}                if ($global:logtoEventlog -eq $true) {Write-EventLog –LogName Application –Source global:eventlogSource –EntryType $elogtype –EventID 1 –Message $logstring -ErrorAction
 Stop}
                Write-Host "[Verbose]$logType $logstring" -ForegroundColor $logColour        } else {            #Check if log is verbose if it is dont log it otherwise log a standard entry            if ($v -eq $true) {                       #Do Nothing            } else {                #Write Standard Log Entry                if ($global:logtoFile -eq $true) {Add-Content $Logfile -value "$TimeStamp$logType $logstring" -ErrorAction Stop}                if ($global:logtoEventlog -eq $true) {Write-EventLog –LogName Application –Source $global:eventlogSource –EntryType $elogtype –EventID 1 –Message $logstring -ErrorAction
 Stop}
            }            #Write Standard Log Entries to Screen if verbose logging is enabled            if ($global:verboselog -eq $true){                Write-Host "$logType $logstring" -ForegroundColor $logColour            }        }    }
}
#######################
#     Parameters      #
#######################
# General    #Current Script Location    $PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition    #Current Time and Date    $TimeDate = Get-Date -Format "yyyy-MM-dd-HH:mm:ss"    #MSI Application ID (required so that Intune knows script package successfully deployed)    #Note: Ensure when creating MSI that the Application ID is the same one defined in this variable.    $ApplicationID = "Deploy Printer Package 1"    #Install Path (Path to unzip driver and script to)    $InstallPath = "$env:PROGRAMFILES" + "\SomePrinter"    #Zip File Name (Zipped up Driver)    $ZipFile = "$PSScriptRoot\PrinterDriver.zip"    #Driver INF to install    $PrinterDriverInf = "Cnp60MA64.INF"    #Path to Inf file for printer driver installation    $InstallDriverPath = $InstallPath + "\" + $PrinterDriverInf    #Printer Name (Seen by End User)    $PrinterName = "Hallo"    #Printer Driver Name (Collect from inside INF file)    $PrinterDriver = “CanoniR-ADV_C7260/7204D4"    #Printer Port Name    $PrinterPortName = “TCPIP:Hallo”
    #Printer IP Address    $PrinterIPAddress = "Left bank for purpose of this topic"    #LPR Queue Name (If Applicable)    $PrinterLPRQueueName = “Secure”
 
# Logging    $Logfile = ($PSScriptRoot + "\Logs\" + $TimeDate + "-DeployPrinter.log")    $global:logging = $true    $global:verboselog = $false    $global:logtoEventlog = $true    $global:logtoFile = $false    $global:logTimeDate = $true    $global:eventlogSource = "Deploy-Printer"    #Start logging and check logfile access try  {  LogWrite "$eventlogSource script started - $TimeDate" -type start }  catch  {        Throw "You don't have write permissions to $logfile, please start an elevated PowerShell prompt or change NTFS permissions" }
#######################
#      Functions      #
#######################
function unzip ($file,$ExtractPath) {    LogWrite "Extracting $file to $ExtractPath" -type i    expand-archive -Path $file -DestinationPath $ExtractPath -Force
}
#######################
#      Execution      #
#######################
try
{    LogWrite "Checking $InstallPath exists if not create path" -type i -v $true    $CheckInstallPath = test-path -path $InstallPath    If ($CheckInstallPath -ne $true) {        New-Item -ItemType "Directory" -Path $InstallPath -Force    }    #Add registry entries so powershell registers as successfully run MSI for MSI deployment    New-Item -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall -Name $ApplicationID    New-ItemProperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$ApplicationID -Name UninstallString -PropertyType String -Value $ApplicationID    #Unzip Printer Driver zip to installation path    LogWrite "Unzip Printer Driver zip to installation path" -type i    $ExtractDriver = Unzip $ZipFile $InstallPath           #Import Printer Driver into Windows Driver Store    #Note: the sysnative path below is required so pnputil can be found when deploying via intune for 64bit OSes.    #if you want to test interactively temporary change the path to system32    LogWrite "Import Printer Driver:$InstallDriverPath into Windows Driver Store" -type i    $PNPUtil = $env:windir + "\Sysnative\" + 'pnputil.exe'    & $PNPUtil /add-driver $InstallDriverPath        #Add Printer Driver so it is available for use to create a printer with    LogWrite "Add Printer Driver: $PrinterDriver so it is available for use to create a printer with" -type i    Add-PrinterDriver -Name $PrinterDriver        #Note: do not create both a standard LPR Port and a Standard TCPIP Port Comment out the port that is not required        #Create LPR Port (Uncomment lines below to create a LPR Port)    #LogWrite "Create LPR Port" -type i    #Add-PrinterPort -Name $PrinterPortName -LprHostAddress $PrinterIPAddress -LprQueueName $PrinterLPRQueueName        #Create Standard TCPIP Port    LogWrite "Create Standard TCPIP Port: $PrinterPortName" -type i    Add-PrinterPort -Name $PrinterPortName -PrinterHostAddress $PrinterIPAddress        #Create Printer    LogWrite "Deploying $PrinterName" -type i    Add-Printer -Name $PrinterName -PortName $PrinterPortName -DriverName $PrinterDriver        #End of Script    LogWrite "$eventlogSource script completed successfully- $TimeDate" -type end
}
catch [system.exception]
{ $err = $_.Exception.Message LogWrite "Unable to deploy printer, `r`nError: $err" -type e    #End of Script    LogWrite "$eventlogSource script completed unsuccessfully- $TimeDate" -type end
}


 


Automate folder/Sub-folders ACL using powershell

$
0
0

Hello Microsoft Community Members,

I am working on a powershell script that automates folder/sub-folders creation. I was able to accomplish this, however, i need to set certain access through automation. I've been looking for answers online, which I tried many of them without success.

Here is my Scenario:

  1. I want to create Project folder, under the main project folder comes sub-folders.
  2. The project root folder should not be altered by anyone except certain project managers (other users cannot add/ remove sub-folders)inside each sub-folder, users can modify whatever they want (Add/Remove/Delete/Create), this can be accomplished through GUI, but i need to make it automated.

What i have done so far, is i was able to take the input from the user (Project folder name, and sub-folders are statically assigned) and automate folder and sub-folders creation, but unable to automate the permissions.

Appreciate any kind of assistance. Thank you!!

Can't connect to remote server

$
0
0

When I attempt to connect to my remote server, from my desktop, via powershell, I get the following message.

I've enabled WinRM via group policy, and verified that it is running on the server. Set my desktop's IP in IPv4 filters. Added it as a trusted host. Tried running the enable-psremoting command. My firewall is off, so I don't think it's being blocked. Does anyone have any other suggestions?

Inconvenience of “Set-ExecutionPolicy RemoteSigned” command

$
0
0

Hi, I am using powershell to parse a comma separated file using the "import-csv" cmdlet.  A batch file calls the powershell script passing parameter of dates in file names to linearly search the csv file and extract information from lines in the csv file matching the date. 

The problem is the inconvenience of having to execute the command “Set-ExecutionPolicy RemoteSigned” as I can't easily give my batch application to someone else who is not tech savvy and expect them to run this command. I am not doing anything that threatens security.  I am thinking I made the wrong choice of powershell and should have chosen to search csv file using bash.

Remote operation privileges

$
0
0

Hello,

I sometimes face this issue when trying to do remote operation via Powershell.

 D:\scripts\lm> get-service -ComputerName krycsmii0001 -Name bigf* | restart-service
get-service : Cannot open Service Control Manager on computer 'krycsmii0001'. This operation might require other
privileges.
At line:1 char:1+ get-service -ComputerName krycsmii0001 -Name bigf* | restart-service+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Get-Service], InvalidOperationException+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand

However Im doing this from a machine where I am logged with domain account and this account is also member of Administrators group on target servers.

what might be wrong pls?

Thanks


--------------------- Leos

2012 R2 Powershell application starts and closes about 3 seconds later

$
0
0

Running a Hyper-V Gen1 VM Workgroup with Windows Server 2012 R2 Standard installed.  VM has 64GB RAM and 4 vCPUs allocated to it.  When I launch the PowerShell application it launches just fine and I get the proper window just like I should but about 3 seconds after it opens the window closes with no error message displayed.

The client has recently asked to have a harden GPO settings applied to the server.  The server was rebooted to apply the settings and checks after the reboot showed that PowerShell was working as it should.  Later the same day is when the issue appeared and as far as I have been able to determine no other changes were made to the server between the time when it was working and the time when it started to have this issue.

I checked the Application and System event logs for any PowerShell related entries and there were none found.  I have run sfc /scannow on the VM and no integrity issues were reported.  I have modified the registry entries identified in the article found at https://stackoverflow.com/questions/1337229/powershell-window-disappears-before-i-can-read-the-error-message to include the -NoExit switch but that did not resolve the issue.

Has anyone encountered this issue previously?   If so, what was done to resolve the issue?


Jerry Ellis

Powershell : Cannot use object linking and embedding

$
0
0

Hi All,

I've a Powershell script to set up user identity of a 32bits DCOM application (Excel 32bits). To do that, I've used a sample of Microsoft Windows SDK for Windows 7  that I've compiled "DComPerm.exe". 

New-Item -Path "$RegPath" -Name "$AppID" -Value "Microsoft Excel Application"
DComPerm.exe -runas "$appId" $DomainUser $Password

Everything seems good, just that I expect Excel to throw this exception when I open it up:

Cannot use object linking and embedding

This happen only if I manually type in cmd "mmc comexp.msc /32" and then browse the 32 bits component service console till I click on DCOM Config which load DCOM objects.

(Which is normal I'm running 32 bits excel application on a 64bits windows machine)

Don’t know how to script that last step, any help will be appreciated ?

Regards,

Accessing SQL server with PowerShell

$
0
0

Hi Folks,

  I am trying to use Invoke-Command to access a data table in my local SQL server instance.

  If I run the command from a powershell window as my account (xyz), it retuns data, but the SQL Server log shows Error 18456, State 5 (Incorrect UserId) - it is showing domain\machine$ as the username.

  If I try and provide a PSCredential the command does not work with a - Login failed for user xyz  (The sql log still reports machine$ as the username, not xyz).

Invoke-SqlCmd -ServerInstance "myserver" -Database "MyDB" -Query "SELECT * FROM dbo.tablex"   # this works

$cred = Get-Credential
Invoke-SqlCmd -Credential $cred -ServerInstance "myserver" -Database "MyDB" -Query "SELECT * FROM dbo.tablex"   # this does not

Invoke-SqlCmd -Credential $cred -Query "SELECT * FROM dbo.tablex" -ConnectionString Data Source=MyServer; Initial Catalog=MyDB;Integrated Security=True;ApplicationIntent=READONLY"  # Also does not work
Can anyone tell me how to get Invoke-Command to use a credential - it is the last version with the connection string that I am interested in.

edit: Updated, typed in the Invoke-Command when I meant Invoke-SQLCmd.

Error when running startup script

$
0
0

Hi, 

I have an issue with a startup script i created for adding a group to the local admin of a computer. 

$ComputerID = (Get-WmiObject -class Win32_bios | select pscomputername).pscomputername

$LocalAdmin = (Get-LocalGroup | Where-Object Name -like -value "Admin*").name

$LocalAdminGroup = (Get-LocalGroupMember -Group $Localadmin | Where-Object Name -like -value "Groupname-$ComputerID").name

If($LocaladminGroup -like "Groupname-$ComputerID")
{
Exit
}

Else
{
Add-LocalGroupMember -Group $LocalAdmin -Member "Groupname-$ComputerID"
}

This script works fine most of the times, but i have noticed when there is a deleted AD group as a member of the local admin group, the script is failing with below error message. 

And here you can see the error message. 

Get-LocalGroupMember -Group "Administrators"
Get-LocalGroupMember : Failed to compare two elements in the array.
At line:1 char:1+ Get-LocalGroupMember -Group "Administrators"+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Get-LocalGroupMember], InvalidOperationException+ FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand


Is there any way to remove old deleted groups/users from the local admin group of computers and inbed it into the script? 

Get-CertificationAuthority is not working

$
0
0

Hello,

I imported PSPKI and PKITools modules,

When try to run "Get-CertificationAuthority -Name myCAname, I get following error message:

Exception calling "EnumEnterpriseCAs" with "2" argument(s): "The system cannot find the file specified"

At C:\Program Files\WindowsPowerShell\Modules\PSPKI\3.4.1.0\Server\Get-CertificationAuthority.ps1:15 char:16

+ ... __NameSet" {[PKI.CertificateServices.CertificateAuthority]::EnumEnter ...

+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : Win32Exception

any thoughts?

Thanks

Need some help with a PowerShell script to delete videos with no "length"?

$
0
0

Hello,

Can someone help me with this?

I want to delete all videos in a folder (extension *.mp4) that does not have a "length"...in essence, deleting all of the videos that are not actually readable video files.

Thanks, any help appreciated.

Powershell Button Help

$
0
0

Hello Forums!

Long time lurker, first time poster. So I am writing a powershell script for work using GUI format. What I am looking to have the script do is in this first window, when you hit the next button, it closes the first window and at the same time opens the second window. But I have yet to have any luck with figuring this out and I can not seem to find an answer Googling around the interwebs. Could any of you more knowledgeable folks please offer some suggestions on where to fix my code?

NOTE: Had to hand jam all this code from another computer so there may be some minor errors

Thanks!

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form1                    = New-Object System.Windows.Forms.Form
$Form1.ClientSize         = '600,600'
$Form1.Text               = "Intro Window"
$Form1.Topmost            = $True
$Form1.ControlBox         = $False

$Label                    = New-Object System.Windows.Form.Label
$Label.text               = "Window 1"
$Label.Location           = New-Object System.Drawing.Point 250,50
$Label.Autosize           = $True
$Form1.Controls.Add($Label)

$Button                   = New-Object System.Windows.Form.Button
$Button.Text              = "Next"
$Button.Width             = 100
$Button.Height            = 30
$Button.Location          = New-Object System.Drawing.Point 250, 500
$Form1.Controls.Add($Button)

#Test code that did not work
function do_exit
{
    $Form1.Close()
    & .\script2.ps1
# Also tried $Form1.Close() | & .\script2.ps1
}
 Button.Add_Click({
    do_exit
})

#Test code 2 that also is not working
$Button.Add_Click({
    $Form1.Close()
    & .\script2.ps1
})

$Form1.ShowDialog()

Powershell simple decode/encode from utf to show correct accents

$
0
0

Hi,

I have this string in a Powershell script and want to show it with the corresponding accents. What do I have to do?

$originalString = "Fuentes de información"

Desired output: "Fuentes de información"

Any help would be really appreciated.

Ricardo

Viewing all 21975 articles
Browse latest View live


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