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

Proper Powershell formatting Where | FriendlyName like $variable

$
0
0

Thanks for reading, I'm working on something a bit outside my element and trying to write a powershell script that can install some SSL Certificates into some Veeam Products.

This works.

Add-PSSnapinVeeamPSSnapinConnect-VBRServer
$certificate =Get-VBRCloudGatewayCertificate-FromStore|WhereFriendlyName-like "*12/10/2019*"Add-VBRCloudGatewayCertificate-Certificate $certificateDisconnect-VBRServer

What I need though is a way for the -like "*12/10/2019*" to be a variable that inserts today's date.

I've tried using a variable like this:

 $date =Get-Date-Format"MM/dd/yyyy"

Then using

-like "*$date*" 

I've tried something like this

-like "*(Get-Date -Format "MM/dd/yyyy")*"

Go easy on me I'm sure I'm missing something dumb and obvious but I'm not a programmer and my scripting skills are pretty minimal.

Thanks for taking a look and helping out.


Copy two separate ranges from same Excel sheet

$
0
0

Hi,

How would I modify the code below to copy two separate ranges (ex tables) from same worksheet? The work sheet has a lot of data presented only two tables need to copied and sent via email? I attempted to do so but only the last declared range gets pasted!

$x1 = New-Object -comobject Excel.Application

$UserWorkBook = $x1.Workbooks.Open("G:\utkarsh-automation-script\statuses\best\test_excel-final.xlsx")

$UserWorksheet = $UserWorkBook.Worksheets.Item(1)

$UserWorksheet.activate()

$rgeSource=$UserWorksheet.range("A3","E6")

$rgeSource.Copy() | out-null

$Results = Get-Clipboard -TextFormatType Html | select -skip 7 | Out-String


$From = 'automation-gdw@apmea.mcd.com’

$To = 'utkarsh.srivastava@capgemini.com'

$Subject = "Test Mail -$(Get-Date)"


$SMTPServer = 'klsmtprelay.mcd.com’

$Body= "This is the test mail<br>

$Results

<br>
Regards,<br>
Username<br>"

Send-MailMessage -From $From -to $To -Subject $Subject -BodyAsHtml $Body   -SmtpServer $SMTPServer


Unable install Az.Subscription module

$
0
0

Hi I am using Power shell 5.1 on Windows 10. Trying to automate Az subscription process using Powershell. The New-AzSubscription is available in Module Az.Subscription but unable to install the module. 

Tried below commands

 Install-Module -Name Az.Subscription -RequiredVersion 0.7.0-preview -AllowPrerelease

Install-Module -Name Az.Subscription

Install-Module -Name Az.Subscription -AllowPrerelease

Getting error

PackageManagement\Install-Package : No match was found for the specified search criteria and module name
'Az.Subscription'.

PS: get-eventlog message export in csv only with file-path

$
0
0

Hi there

We had some HDD issue and want to output all the lost data.
So with this command I get the messages I wanted but also with unnecessary information. What I'm looking for is an csv-output with just the path for a better overview.

Here is the command that is working successfully:

Get-EventLog -LogName System -EntryType Warning -Source NTFS -Message *File* | export-csv c:\temp\ntfscorrupt_all.csv

We have these log entries:

{Delayed Write Failed} Windows was unable to save all the data for the file \work\example\test.docx The data has been lost. This error may be caused by a failure of your computer hardware or network connection. Please try to save this file elsewhere.

So what option do I have to use, to get only the paths in the csv file like: \work\example\test.docx, \work\example\number2.docx....



Importing data into Skype/Teams

$
0
0

Hi 

In our organisation we are updating our list of emergency locations in the admin section of Teams.

We were able to export the current out of date list using 

Get-CsOnlineLisLocation | Select-Object companyname, description, HouseNumber, Streetname, City, p
ostalcode | Export-Csv c:\temp\skypelocation.csv -NoTypeInformation -Append

We now have the correct up to date list populated in a CSV and we would like to know if its possible to import this back to teams?

There is no import-CsOnlineLisLocation command so I am unsure if this is even possible.

Is there a way to use import-csv and then pipe it into the New-CsOnlineLisLocation command?

Exporting Outlook contacts to csv file

$
0
0

Hello All,

I know I can easily export Outlook contacts to a CSV file manually, but I am looking for an automated way to do this. Some sort of script that will export the Outlook contacts to a CSV file daily without having to do anything manually. Our plan is to export the Outlook contacts and import them into another database platform, using that CSV file.

Anyone know how to do this or if it is even possible?

I tried to replace characters for files in a folder and its sub-folders with a powershell command and kinda messed somethings up.

$
0
0
SO total noob to powershell. I used get-childitem -recurse | rename-item -newname { $_.name-replace ".","_"}. Not all but a lot of file and folder names look like this _____________. Am I screwed or is there a was to "undo" my screw up. I have the ConsoleHost_history.txt file 

Run Powershell Command as Administrator on Remote Computer

$
0
0

Hi,

Can someone please assist me in running powershell command as an administrator on remote computer. I am running below command on remote computer but its not providing the desired results. It does not throw any error or it achieves the desired result.

Invoke-Command -ComputerName $servername -scriptblock {control.exe "intl.cpl,,/f:`"c:\myregionalcfg.xml`""}

I am trying to change the system locale on windows 7 machine remotely.

c:\myregionalcfg.xml file is available on the remote computer.



Need help creating GUI to select folder, but that looks like OpenFileDialog, not using the CommonOpenFileDialog

$
0
0

I have limitations in my company about running exe's and compiling them, so I can't compile an exe from C to run my script. Running it via Visual Basic, using Express, is fine, I can run the exe created by my project but doing an import of dlls that then get compiled into one package is a no-no.  The thing is that my entire project bin folder would need to go from pc to pc to run my app.  Not useful.  So I switched to Powershell.  Since it is a scripting language, I can add-type the dll and run that way...it's allowed.  The problem I have is I still need to keep the dll accessible.  The app was just a simple front end to robocopy.  We do a lot of file copying for database requests and app releases, so we also need to verify timestamps and such.  I found the memory usage of the app via Powershell to be insignificant when compared to VB.  The problem is, I still need to carry around the dll for the CommonOpenFileDialog.  I saw on stackoverflow an old thread about using the OPENFILENAME interface, but I've never used interfaces in Powershell and I'm reading that it is not a small feat to do so.

http://stackoverflow.com/questions/31059/how-do-you-configure-an-openfiledialog-to-select-folders

The issue I have is that the To and the From may be UNC paths and well the standard OpenFolderDialog is in tree form and is only usable for local drives.  The thing is that the other day adding my Quick Launch folder to my desktop bar, I saw this:

So that means somewhere, there is a namespace, class, whatever that lets me do this OEM. How can I do this, using what already comes with windows?

This is my current code for this piece (the entire code is large):

#Create From Button
$btnFrom = New-Object System.Windows.Forms.Button
$btnFrom.Location = New-Object System.Drawing.Point(390, 20)
$btnFrom.Size = New-Object System.Drawing.Size(67, 27)
$btnFrom.TabIndex = 1
$btnFrom.Text = "Browse"
$btnFrom.UseVisualStyleBackColor = $true

#Add From Button Click actions
$btnFrom.add_Click({
    #In the case the user clicks cancel from this dialog, so it won't double file names
    $lstFiles.Items.Clear()

    #Create OpenFileDialog object
    $ofdFrom = New-Object System.Windows.Forms.OpenFileDialog
    $ofdFrom.Multiselect = $true
    $ofdFrom.Title = "Please select the source files"
    #If this is not the first run of the OFD, then it will use its last path as the initial one
    if($strFromPath -ne [String]::Empty){
        $ofdFrom.InitialDirectory = $strFromPath
    }

    #Show the OFD and if it exists successfully it will add the names of the file(s) selected to lstFiles
    if(($ofdFrom.ShowDialog() = [System.Windows.Forms.DialogResult]::OK) -And ($ofdFrom.SafeFileNames.Count -ne 0)){
        $ofdFrom.SafeFileNames.ForEach({
            $lstFiles.Items.Add($_)
        })

        #Extract path from the files selected, to display in its respective TextBox
        $Script:strFromPath = $ofdFrom.FileNames[0]
        $Script:strFromPath = $strFromPath.Substring(0, $strFromPath.LastIndexOf("\""))
        $txtFrom.Text = $strFromPath
    }
})

#Create To Button
$btnTo = New-Object System.Windows.Forms.Button
$btnTo.Location = New-Object System.Drawing.Point(390, 63)
$btnTo.Size = New-Object System.Drawing.Size(67, 27)
$btnTo.TabIndex = 2
$btnTo.Text = "Browse"
$btnTo.UseVisualStyleBackColor = $true

#Add To Button Click actions
$btnTo.add_Click({
    #Create COFD object
    $fsdTo = New-Object Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog
    $fsdTo.EnsureReadOnly = $true
    $fsdTo.IsFolderPicker = $true
    $fsdTo.AllowNonFileSystemItems = $false
    $fsdTo.Multiselect = $false
    $fsdTo.Title = "Please select the destination directory"

    #If this is not the first run of the OFD, then it will use its last path as the initial one
    if($strToPath -ne [String]::Empty){
        $fsdTo.InitialDirectory = $strToPath
    }

    #Show the COFD and if it exists successfully, strToPath will be updated with the path that was selected
    if($fsdTo.ShowDialog() = [Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult]::Ok){
        $Script:strToPath = $fsdTo.FileName
        $txtTo.Text = $strToPath
    }
})



Logging into a windows Account

$
0
0

Hello

My windows images contain a local admin account.

Is there any way that I can have powershell login to windows using that admin account once the image is finished being applied?  Then log out.  Just so that the local user profile is created.

Thank You

Terry


Powershell Script to Delete Users Profile if placeholder file is older than 30days

$
0
0
File server with folder structure as follows:
DATA$(Top Level Share)
 Folder1
 Folder2
 Folder3
 etc
 etc


Check each subfolder of Data$ for the existence of a text file named "mig.txt"
If "mig.txt" doesn't exist
 Then Do Nothing
If "mig.txt" exists
 Check "mig.txt" creation date
If creation date is over 30days ago
 Delete contents of subfolder

I want to run the above as a scheduled Task once a day from the file server


progress bar color issue

$
0
0

Here is the code I am using:

$services = Get-Service
$count=$services.Count
For($i = 1; $i -le $count; $i++)
{

Write-Progress -Activity "Status is .." `
-PercentComplete (($i*100)/$count) `
-Status "$(([math]::Round((($i)/$count * 100),0))) % completed!"
$Host.PrivateData.ProgressBackgroundColor=’Blue’
$Host.PrivateData.ProgressForegroundColor=’Red’

Start-Sleep -Seconds 1

}

Script is unable to change the color of the progress bar.

Thank you in advance for any assistance in resolving this issue!


Leon Pearlman

How to copy Excel pivot charts to an email using PowerShell

$
0
0

Hi,

How can I copy a chart or more from an Excel sheet and paste to an Outlook email?

Thank you!



Error setting certain Windows Defender settings on Windows Server 2019 Standard

$
0
0

Running the following cmdlet on a Setting that is in the "NOTSET" state works fine, after setting it to Enable/Disable using the following powershell cmdlet:

Set-ProcessMitigation -System -Enable SEHOP

I get this error:

Set-ProcessMitigation : Destination array was not long enough. Check destIndex and length, and the array's lower
bounds.
At line:1 char:1
+ Set-ProcessMitigation -System -Enable SEHOP
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Set-ProcessMitigation], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.Samples.PowerShell.Commands.SetProcessMitigationsComm
   and

and I am unable to ever change the setting again using PowerShell commands. The same process works without issue on Windows 10, the issue only seems to exist on Server 2019. Changing the setting using the Windows Security GUI works as expected.

For other controls, such as DEP, CFG,  I still get the error, but the command applies the new setting properly anyway. So far SEHOP is the only setting that is unchangeable, but there may be others as we haven't tested extensively yet. It fails for both System and App level settings.

Extracting XML element values using PowerShell

$
0
0

For how simple this is, I have not been able to find a solution.

Take a simple XML file like the below where each element has a value and no attributes within the <> - 

<Objects><Event><ComputerName>Computer1</ComputerName><UserName>User1</UserName></Event><Event><ComputerName>Computer2</ComputerName><UserName>User2</UserName></Event></Objects>

I can easily extract this data into a table by using the following PowerShell command - 

$xml = Select-Xml -Xml ([XML]($File | Get-Content)) -XPath *; $xml.node.event

And I get the following output - 

ComputerName UserName
------------ --------
Computer1    User1
Computer2    User2

All well and good.  Well, I have some log files I want to parse where each element has both attributes in the <> and values.

So for my example, let's modify the XML slightly so that the elements now also have an attribute inside the <> - 

<Objects><Event><ComputerName attribute="1">Computer1</ComputerName><UserName attribute2="1">User1</UserName></Event><Event><ComputerName attribute="2">Computer2</ComputerName><UserName attribute2="2">User2</UserName></Event></Objects>

I try running the same PowerShell command again -  

$xml = Select-Xml -Xml ([XML]($File | Get-Content)) -XPath *; $xml.node.event

And the output is now bizarre and quite meaningless - 

ComputerName UserName
------------ --------
ComputerName UserName
ComputerName UserName

So my question is quite simple (and hopefully the answer is too!).  How do I get the same output as I did in my first example, when the XML is formed as per my second example?


David



Veracode Scan report there is a serial security flaw in the system.management.automation 6.1.7601.17515

$
0
0
Our product provide a powershell operation interface for the Customer, these function target to .NET Framework  and based on Microsoft system.management.automation 6.1.7601.17515, ,  But the a code security analysis tool VeraCode Scan report there is a serious security flaw. 

The veracode report shown as below:

Description

Improper Neutralization of Special Elements used in an OS Command

Description

This call contains a command injection flaw. The argument to the function is constructed using untrusted input. If an attacker is allowed to specify all or part of the command, it may be possible to execute commands on the server with the privileges of the executing process. The level of exposure depends on the effectiveness of input validation routines, if any.

Recommendations

Validate all untrusted input to ensure that it conforms to the expected format, using centralized data validation routines when possible. When using black lists, be sure that the sanitizing routine performs a sufficient number of iterations to remove all instances of disallowed characters. Most APIs that execute system commands also have a "safe" version of the method that takes an array of strings as input rather than a single string, which protects against some forms of command injection.

Instances found via Static Scan

Flaw Id Module Location Exploitability Fix By
105system.management.automation.dllvoid ConnectAsync() 76%Likely9/11/19


We don't sure if the DLL really has this security flaw, or the Veracode scan tool report it by a mistake?
Though the latest version of this DLL has not this flaw, but it is based on latest version of  .NET Core. And our product based on .NET Framework. Move it from the .NET Framework to .NET Core means lots of work. So we want to check if it is really a security flaw?  If sure, can you please give some advice about how to enhance the security?  Thanks. 

Append Names to DisplayName with Powershell

$
0
0

HI.  

 I need to append FirstName and SurName to the existing DisplayName in AD.

All Admin accounts, which start with SVC  (so Svc6655 for example) need to be changed to show 

SVC6655 - FirstName SurName

Thanks in advance

Unzipping duplicate files in separate folders

$
0
0

Hi,

I wonder if someone could help please,

I have a task of unzipping over 5k zipped files. The following command does this, however some of the zipped files have duplicate content. I would like to have all duplicate content unzipped into a separate folder. Can some advise how this can be achieved?

Thank you

Rick

Function ZipEverything($src, $dest)
  {
        Add-Type -AssemblyName System.IO.Compression.Filesystem
        $zps = Get-ChildItem $src -Filter *.zip


    foreach ($zp IN $zps)
    {
        $all = $src + $zp
        [System.IO.Compression.ZipFile]::ExtractToDirectory($all, $dest)
    }

 }

    ZipEverything -src "C:\Support Team\Extract PS Script\Source\" -dest "U:\Support Team\Monthly Reports\Extract PS Script\Target\"


    # Open Target folder
explorer "C:\Support Team\Extract PS Script\Target\"

How To get anti-virus exclusion list using cmd or powershell?

$
0
0
I want to list all excluded files/folder using cmd or powershell

Filter out Windows Server and Laptops

$
0
0

Hi,
I am trying to write a script to shut down all Desktops.
I want to filter out Servers and Laptops to a variable which will not be shut down.  
I can achieve filtering out all machines with Windows client OS using the below:
$computer = Get-ADComputer -SearchBase "DC=domain,DC=local" -Filter 'operatingsystem -notlike "*Windows Server*" -and enabled -eq "true"'

But how can I filter out all laptops.  Probably using the below:
$typ=Get-WmiObject win32_computersystem | PCSystemType

But, how would i be able get the whole $computer and $Type to pipe or concatenate or join to a single variable with only desktops?

Appreciate any assistance.

Viewing all 21975 articles
Browse latest View live


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