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

Split an array of string and flatten into single array

$
0
0

I have a following array of strings

$array = @("asdf asdf","aaa ddd","cccc a","aaaa dd")

and I would like to split every element of that array by a new line and put the result into  array

So expected result should look as follows

@("asdf", "asdf", "aaa", "ddd", "cccc", "a", "aaaa", "dd")

I would like to avoid using nested foreach statement and preferably use some kind of SelectMany syntax

So far I've tried 

$result = $array | %{$_.Split([Environment]::NewLine)}  
$result = $array | Select-Object -ExpandProperty $_.Split([Environment]::NewLine)

but with no luck. Any thoughts?






How to execute button action when powershell script starts

$
0
0

Hello Forum,

I have a PowerShell that creates a gui app with some buttons on the app.  When the app loads I have a Search button with the following code behind it to build the search parameters:

Function Search-ObjectName()
{
    $ErrorProvider.Clear()
    If($tbObjectName.Text.Length -eq 0)
    {
        $ErrorProvider.SetError($tbObjectName, 'Please enter a search name.')
    }
    Else
    {
        $lbObjectName.Items.Clear()
        $ObjectName = $tbObjectName.Text -split ','
        ForEach($o in @($RBObjectTypeA, $RBObjectTypeB, $RBObjectTypeC))
        {
            If($o.Checked)
            {
                $ObjectType = $o.Text
            }
        }
        $PMObjects = @()
        $PMObjects = Get-MonitoringObjects -ObjectType $ObjectType -ObjectName $ObjectName -ManagementGroup $MG -GUIList
        If($PMObjects)
        {
            $lbObjectName.BeginUpdate()
            ForEach($PMObject in $PMObjects)
            {
                $lbObjectName.Items.Add($PMObject.DisplayName)| Where{$lbObjectName -match "xyzcompany.*"}
            }
            $lbObjectName.EndUpdate()
        }
    }
}

In my Windows Forms Assembly section I've added this bit of code to build the Search button:

    $btnSearchObjectName = New-Object System.Windows.Forms.Button
    $btnSearchObjectName.Name = 'btnSearch'
    $btnSearchObjectName.Location = New-Object System.Drawing.Size(250,95)
    $btnSearchObjectName.Size = New-Object System.Drawing.Size(60,20)
    $btnSearchObjectName.Text = 'Search'
    $btnSearchObjectName.TabIndex = 3
    $btnSearchObjectName.Add_Click({Search-ObjectName})

How would I execute the pressing of the Search Button at startup?  Right now my app works in that the groupbox is empty but the user can press the Search button and the results are displayed.  But what I'd like to have happen is when the user opens the app the search results are already displayed.  What code do I need to add...and to where do I add this code to have the Search button executed when the app opens?

Thank you in advance for any help you can provide.


Help convertto-json CSV file

$
0
0

Hi, i have the $CSV File like..

email                      role   
-----                      ----   
user1@contoso.com members
user2@contoso.com   members
user2@contoso.com owner  
user3@contoso.com   manager

If i convert it to Json iget the format:

[
    {
        "email":  "user1@contoso.com",
        "role":  "members"
    },
    {
        "email":  "user2@contoso.com",
        "role":  "members"
    },
    {
        "email":  "user2@contoso.com",
        "role":  "owner"
    },
    {
        "email":  "user3@contoso.com",
        "role":  "manager"
    }
]

But i  would like to get it as:

    {
        "email":  "user1@contoso.com",
        "role":  "members",
        "email":  "user2@contoso.com",
        "role":  "members",
        "email":  "user2@contoso.com",
        "role":  "owner",
        "email":  "user3@contoso.com",
        "role":  "manager"
    }

Is there a way to conver to this format??

Thanks

Get Files and Folders from SharePoint Document Library

$
0
0

Hi Guys,

I'm new to PowerShell, I need to loop through a document library and get metadata of the files and folders.

I'm looking also for empty folders to delete them.

I was able to get something working but not the document library see my code below

cls

#Using PnP PowerShell Cmdlets
#Get Connection Credential
$User = "myuser@username.com"
$File = "C:\Users\myuser\OneDrive - username\mycompany\PowerShell\MyPassword.txt"
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)

#connect to the pnp extension
Connect-SPOnline -Url https://my.sharepoint.com -Credentials $Cred

#Get-help Get-SPOList -Examples
Get-SPOList | Format-Table


#get-help Get-SPOList -Examples

#Get-Help Get-PnPFolder -Examples



Codernater

Get all blobs name from Azure Storage

$
0
0

Hi guys,

I'm trying to get the files metadata or at least the name of the files from the blob storage.

I keep getting the following error, could you please tell me what I am doing wrong? 

Get-AzureStorageBlob : Could not get the storage context.  Please pass in a storage context or set the current storage context.
At line:16 char:10
+ $blobs = Get-AzureStorageBlob -Container $ContainerName
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzureStorageBlob], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.GetAzureStorageBlobCommand

Here is my PS Syntax.

Clear-Host
$SubscriptionName = "MySubscriptionName"
$StorageAccountName = "MyStorageAccountName"
$StorageAccountKey = "MyStorageAccountKey"
$ContainerName = "MyContainerName"

#Set up the storage account context
$ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey

Get-AzureStorageContainer -Context $ctx

$blobs = Get-AzureStorageBlob -Container $ContainerName

$blobs


Codernater

Bug in PS Import-PfxCertificate - Verify?

$
0
0

I have run into an insidious bug with the Import-PfxCertificate on Windows 2012 R2. When attempting to use this cmdlet, the certificate and cert authority that signed it are successfully imported, but the private key is not. What makes this totally crazy is that the command succeeds, and even the HasPrivateKey bit is set, but the PrivateKey value is null. A long time ago when I ran into this problem I switched to running certutil to do the import instead, and that worked all the way up till now, and evidently the timing/downstream mechanism that is calling certutil (we do this in AWS EC2 during instance bootstrap) has changed in a way that makes this command also succeed but generate bogus private key data. Here is an example of the boom:

Import-PfxCertificate -CertStoreLocation cert:\LocalMachine\My -Password $pw -FilePath C:\PropertyFiles\my_cert.pfx

This cmdlet generates no errors and does product a certificate entry. When I look at the cert details I get the following:

PSPath                   : Microsoft.PowerShell.Security\Certificate::LocalMachine\My\A2455AA3A4D4E553B3FF4023DEE2B49F9
                           9638827
PSParentPath             : Microsoft.PowerShell.Security\Certificate::LocalMachine\My
PSChildName              : A2455AA3A4D4E553B3FF4023DEE2B49F99638827
PSDrive                  : Cert
PSProvider               : Microsoft.PowerShell.Security\Certificate
PSIsContainer            : False
EnhancedKeyUsageList     : {}
DnsNameList              : {IR_SDK_CERT}
SendAsTrustedIssuer      : False
EnrollmentPolicyEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
EnrollmentServerEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
PolicyId                 :
Archived                 : False
Extensions               : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid}
FriendlyName             : ir_sdk_cert
IssuerName               : System.Security.Cryptography.X509Certificates.X500DistinguishedName
NotAfter                 : 12/9/2021 6:23:17 PM
NotBefore                : 12/9/2016 6:23:17 PM
HasPrivateKey            : True
PrivateKey               :
PublicKey                : System.Security.Cryptography.X509Certificates.PublicKey
RawData                  : {48, 130, 3, 173...}
SerialNumber             : 008D8EA7B711E7ED508CA6550E0E1EF0E8
SubjectName              : System.Security.Cryptography.X509Certificates.X500DistinguishedName
SignatureAlgorithm       : System.Security.Cryptography.Oid
Thumbprint               : A2455AA3A4D4E553B3FF4023DEE2B49F99638827
Version                  : 3
Handle                   : 1008768248560
Issuer                   : C=US, S=NY, L=New York, O=Infor, OU=Infor Labs, CN=IR_CA_ir-certgen-lambda-ca2
Subject                  : C=US, S=NY, L=New York, O=Infor, OU=Infor Labs, CN=IR_SDK_CERT

Note that the HasPrivateKey attribute is set to True, but PrivateKey is null. On a valid import, PrivateKey should be  System.Security.Cryptography.RSACryptoServiceProvider. If I run certutil -importpfx -p password C:\PropertyFiles\my_cert.pfx AFTER the system has bootstrapped, this value has been filled in, and the cert is usable by a .NET app that's trying to utilize it. However, in _all_ cases in PS and in the bootstrap case with certutil, this is blank.

Can I get a verification that this is a bug, and any potential other alternate workarounds, I would very much appreciate it.

Thanks!

Donavan


No more PRINT on MSDN screens

$
0
0
Why did you remove the PRINT page function???????????

How to launch webserver without notifications from firewall?

$
0
0

Hello!

Please tell, how to launch xampp web server without appearance of a firewall messages which tells that he blocked some functions of Apache and Mysql servers in all public and private networks? Apache and Mysql servers are launched by xampp_start.exe application which should be launched by my powershell scrypt



Export-csv

$
0
0

Hello all, I have been searching on this for a few hours but cannot find a fix. All I want to do is export the findings of these OUs.

Get-ADComputer -Filter * -SearchBase "OU=Laptops,OU=ITS,OU=COM,DC=OURS,DC=LOC,DC=OO,DC=us" | Select-Object Name 
Get-ADComputer -Filter * -SearchBase "OU=Desktops,OU=ITS,OU=COM,DC=OURS,DC=LOC,DC=OO,DC=us" | Select-Object Name
Get-ADComputer -Filter * -SearchBase "OU=Desktops,OU=ITS,OU=COM,DC=OURS,DC=LOC,DC=OO,DC=us" | Select-Object Name

Export-CSV c:\users\xxxxxxx\desktop\its.csv

When I run this it returns

cmdlet Export-Csv at command pipeline position 1
Supply values for the following parameters:
InputObject: 

If I do it like this it works but need to export it to separate .cvs

Get-ADComputer -Filter * -SearchBase "OU=Desktops,OU=ITS,OU=COM,DC=OURS,DC=LOC,DC=OO,DC=us" | Select-Object Name | Export-CSV c:\users\xxxxxxx\desktop\its.csv

What am i missing?

Thanks, Joe

Migrating email aliases

$
0
0

Hi we are moving from one office 365 (not synced, cloud only) to another which is ad synced and has an onsite exchange server for admin only. I'd like to export all of our current users email aliases then import them on the exchange 2016 server which syncs with o365.

Someone mentioned to me try:

Get-Recipient -ResultSize Unlimited | Export-Clixml C:\Recipients.xml 

then copy xml to exchange server

then from exchange run:

$recipients = Import-CliXml "C:\Recipients.xml"

$Recipients|where{$_.RecipientType -eq "UserMailbox"}|foreach{Set-MailUser -EmailAddresses:$_.EmailAddresses -PrimarySMTPAddress:$_.PrimarySMTPAddress}

but i get:

cmdlet Set-MailUser at command pipeline position 1
Supply values for the following parameters:
Identity:

Not sure if theres a different way we could do this?

I've seen this to export might be better but not sure how to import....

Get-Mailbox -ResultSize Unlimited |Select-Object DisplayName,PrimarySmtpAddress, @{Name="EmailAddresses";Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq "smtp"} | ForEach-Object {$_.SmtpAddress}}} | Export-Csv email-addresses.csv


Powershell Help Request - getting error Add-VMNetworkAdapterExtendedAcl : Cannot convert 'System.String[]' to the type 'System.String' required by parameter 'RemoteIPAddress'. Specified method is not supported.

$
0
0

Hi All

I wonder if anyone can help me in a late night and stressful attempt to get something working :)

so the extended port acls below are what i'm trying to apply and in particular i get this error on the last line of code

error Add-VMNetworkAdapterExtendedAcl : Cannot convert 'System.String[]' to the type 'System.String' required by parameter 'RemoteIPAddress'. Specified method is not supported.

in the $servers.ipaddresses array there is like a dozen ip addresses which i want to apply in turn to each vm? using the bold command below

Any suggestions how i can fix this error please?

------------------------------------------------------------------------------------------------------------------------

#Collating VM Names and IP Addresses (Minus Replicas)
$servers = get-vm "test*" | ?{$_.ReplicationMode -ne “Replica”} | Select -ExpandProperty NetworkAdapters | Select VMName, IPAddresses

#Filtering Blank Entries
$servers = $servers | Where-Object {$_.ipaddresses -ne $null}

# Adding PORT ACLS to Environment Servers
foreach ($server in $servers) {
Write-Host "

#Doing Server " $server.VMName
# Block all IP's outgoing to Environment VMs
Add-VMNetworkAdapterExtendedAcl -vmname $server.vmname -VMNetworkAdapterName domain –Action Deny –Direction Outbound –Weight 1
# Block all IP's incoming to Environment VMs
Add-VMNetworkAdapterExtendedAcl -vmname $server.vmname -VMNetworkAdapterName domain –Action Deny –Direction inbound –Weight 2
# Allow RDP 
Add-VMNetworkAdapterExtendedAcl -vmname $server.vmname -VMNetworkAdapterName domain –Action allow –Direction inbound -localport "3389" -protocol "TCP" –Weight 100 -Stateful $true 

#Allow all local IPs outgoing from Performance Servers
Add-VMNetworkAdapterExtendedAcl -VMName $server.vmname -VMNetworkAdapterName domain -LocalIPAddress any -direction Outbound -Action Allow -weight 101

Add-VMNetworkAdapterExtendedAcl -VMName $server.vmname -VMNetworkAdapterName public -RemoteIPAddress $server.ipaddresses -direction inbound -Action Allow -weight 102
}

Powershell automate Post of file on Website but unable to close Website popup windows close or ok

$
0
0

Good day, please help

i am trying to automate the uploading of files to a website.

1. requires to login > close popup "welcome message box" close window

2. then select upload link > then select which upload toggle button option > click upload liink > then again OK on "upload message" popu box

i got to the point where i login but i cant seem to get to the close "X" window on "welcome" popup messge window after login

probably going to have the same issue on the popup window when upload

i checked the html source but dont find the "X"button on form as its a form window with no button and i got the script to close the window but it closes all the windows including the main window i want to upload files

Import-Module wasp $url = 'http://page/login.seam' $username = $args[0] $password = $args[1] $ie = New-Object -COM InternetExplorer.Application -Property @{ Visible = $true Navigate = $url } while ($IE.Busy -eq $true) { # System Sleep/Wait Start-Sleep -Seconds 5 # Focus window iexplore $window = Select-UIElement -ProcessName iexplore # Close Alert key stroke $window | Send-UIKeys '{ESCAPE}' } # LOGIN page $ie.Document.textbox $ie.Document.getElementById("j_id:nick").value = "test" $ie.Document.getElementByID("j_id:submit").Click()

## TRYING TO CLOSE THE POPUP WELCOME WINDOW WITH NO BUTTONS BUT A FORM CLOSE $ie.Document.getElementByID("j_id36:j_id40").Click() $ie.Document.getElementByID("j_id36:messagesPanelFirstHref").Click() ## close IE #Get-Process -name iexplore | Foreach-Object { $_.CloseMainWindow() } #$ie.Quit() #[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie)


Please any help, i would need more help after this as i dont know how choose on option toggle which upload file i want to choose but i want to get past this hurdle first.

Regards

Get-WBSummary for multiple backup sets

$
0
0

Hello Everybody,

I hope someone can help me with a (i thought Simple) Powershell Problem.

Im currently configuring Windows Server Backup on a Hyper-V Server 2012 Standard.

After reading through the best-practises i configured my Hyper-V host to backup the Vms by using the -hyperv switch and it works great (although i havent tested a restore yet).

The Problems im facing now is trying to figure out a way to get my backup results into our monitoring tool (PRTG). For single machines i usually just use Get-WBSummary wich gives me all the information i need. But now on this Hyper-V host by backing up multiple machines the summary of the last backup is not enough anymore. Sadly there is no switch / filter im able to find to get a WBSummary result for the backed up hyper-v vms.

Is there anyway to get WBSumamry like results for each backupset? ( Get-WBBackupSet | GEt-WBSumamry sadly won't work :-) ).  Expecially intresting would be the LastBackupResultHR, DetailedMessage and  LastSuccessfulBackupTime

Thanks in advance

IF statement and loop

$
0
0

Hello PowerShell smart people..

I am working on a little project where I want to remotely execute an .exe with switches and parameters when a computer connects to the network. Here is the PowerShell I have so far.

## Declare credentials
$username = "username"
$password = cat C:\mysecurestring.txt | ConvertTo-SecureString
$cred = New-Object -TypeName System.Management.Automation.PSCredential '
        -argumentlist $username, $password '

## Test if computer is online
If (Test-Connection 192.168.1.100)

## If computer is online then connect to it remotely in PowerShell
    {
    Enter-PSSession -ComputerName hostname -Credential $cred

## Execute command for program
    Invoke-Command -ScriptBlock {program.exe -parameter 1 /f /s -parameter 2}
    }

I have successfully been able to manually run the Enter-PSSession and get to a shell on the remote computer. From there I am successfully able to execute "program.exe -parameter 1 /f /s -parameter 2". Now the goal is to automate the process. The Test-Connection should listen on the network for the IP to come online. Once it does then a Enter-PSSession should be established and the program.exe executed. Sometimes the program.exe will quit but I will still be connected to the remote PowerShell session. I would like the .exe to restart if it quits. Once the computer goes offline, I want the PowerShell to go back to listening and waiting for it again.


Thanks in advance for the assistance.

Version of PowerShell on different OSes?


read line by line and search for multiple strings

$
0
0

Hi ,

Please could you advise that how can i perform below:

i have file in which if string entries are present then i need not to append the string otherwise i need to append.

Contents of File is something like this

www.google.com  1st url

www.bing.com 2nd url

www.msn.com 3rd url

Need to search in whole file and then only append the values..Please suggest


Umeed4u

lastLogonTimestamp: How to return true NULL instead of those 01.01.1601 4:00:00 for users who never logged in?

$
0
0

Hello all, can you please help to change the script to return true NULL instead of those 01.01.1601 4:00:00 for users who never logged in?

I assume it can be done via using some IF check.

The script that I use is from this forum:

Get-ADUser -Filter * -SearchBase "ou=users,dc=contoso,dc=local" -ResultPageSize 0 -Prop CN,lastLogonTimestamp | Select CN,@{n="lastLogonDate";e={[datetime]::FromFileTime($_.lastLogonTimestamp)}} | Export-CSV -NoType last.csv


MCP



How to get data from Powershell with the "Method" variables similar to "Property" values.

$
0
0

Hi All,

I have a question, Searched in the search engines but i did not find the relevant answer, Not sure if my search query was correct.

I have a command in powershell which i run post importing a module which is related to a Microsoft application.

Command: Get-SCOMAgent | Get-Member

So below is the output of the command:

For example if i use the command: Get-SCOMAgent | Where-Object {$_.Networkname - Like "XYZ"} | Select Networkname
Here i used a "property" in filtering the command.

This will give me the filtered data of the network name matching the criteria,

Similarly i want data from the "Method" Values as well. so i used the below which is obvious it will not work as i am doing it the wrong way, But wanted to show what i am exactly looking to pull out:

Get-SCOMAgent | Where-Object {$_.GetPrimaryManagementServer - Like "SCOGPRDCGY001"}

Does any one know how can i do this  or any articles which talk on how to get the values / data from a "Method" Variable ?


Gautam.75801



Trouble Replacing String with Get-Content

$
0
0

Hi, 

I'm looking to edit a config file by replacing an entire line within it so long it begins with server=, but the the script is adding to end of server= instead of replacing the entire line. How can I fix this?

Thanks,

Dan

$user='user1,user2'
$apppath="c:\users\$i\appdata\roaming\app\app.ini"
$getapp= get-content c:\users\$i\appdata\roaming\app\app.ini
Foreach ($i in $user){
If
(($getapp -like 'server=*'))
{($getapp) | ForEach-Object { $_ -replace 'server=', 'server=server.local'} | Set-Content $apppath}
else
{add-content $apppath 'server=server.local'}
}

Extract data from string file returned from System.Net.WebClient

$
0
0

I'm using Powershell to send a SMS through a SMS Gateway provider.  The sending works great this is the last line of my code: 
$wc.DownloadString($url) | Out-File C:\result.txt
the result.txt looks like this:

{
    "message-count": "1",
    "messages": [{
        "to": "11234567899",
        "message-id": "0D0000001B0AB5ED",
        "status": "0",
        "remaining-balance": "1.92020000",
        "message-price": "0.00570000",
        "network": "310004"
    }]
}

The only part I care about is the status in this case it's a zero, but it could be a two-digit number.  I'd like to extract just the value of the status line and put that in it's own file called r.txt  With r.txt containing just the 0

Is this possible and if so could someone get me pointed in the right direction.

Thanks,
Kevin


Viewing all 21975 articles
Browse latest View live


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