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

JEA and GMSA

$
0
0
I have a service management application that can run powershell scripts.  Our plan is to use this application to run powershell scripts that will create and modify user accounts.  Our application connects to Windows servers using WinRM - so most of the time I'm experiencing the 'second-hop' problem.  JEA to the rescue for that problem.  So I created a non-admin, user account and use that account as my JEA RunAsVirtualAccount.  This all is working for me; I can create an AD account and Exchange email.  My problem is I cannot modify the ACL for my newly created user's home drive - a network share.

I have given my RunAs account proper permissions to create and modify home drives,  I can test all this by logging into the server with my RunAS account and running my script - so I know I have the script and permissions set properly.  However, as my JEA is configured presently using a virtual account, when it runs the same script, the account cannot modify the share ACL because it is created as a local system account.

It appears to me that I need to use a GMSA to be able to modify the network share, the user's home drive.  According to JEA Security Considerations, Group managed service accounts (gMSAs) are useful when a member server needs to have access to network resources in the JEA session.

I don't know how to set this up in my JEA configuration.  I have successfully created my GMSA account and allowed servers, but I don't understand

how to use this account within JEA
how do I test it all
I've created my JEA configuration using examples in:

Just Enough Administration (JEA) - Part 1: Overview
Just Enough Administration (JEA) - Part 2: An example
Using this method and my RunAs account, I can test by entering the session using a command such as:

Enter-PSSession -ComputerName <targetcomputer> -ConfigurationName JEA_DNS_OperatorSession -Credential $credential
If I were to use my GMSA account, how can I Enter-PSSession?  The Get-Credential cmdlt prompts for username & password.  A GMSA account has an automated, system generated password.

script to send email to user with their multiple email addresses

$
0
0

Hi 

i got the script below which mainly email users about their current SMTP addresses (multiple ones) and ask them which one they dont need

$Msg.To.Add($ToAddress)
$Msg.Subject = "Email Addresses Clean up"
$Msg.Body = $EmailBody
$Msg.IsBodyHTML = $true
$Smtp.Send($Msg)
}
# Define local Exchange server info for message relay. Ensure that any servers running this script have permission to relay.
$ExchangeServer = "mail.hwl.com.au"
$FromAddress = "it.helpdesk@hwle.com.au"
# Import user list and information from .CSV file
$Users = Import-Excel testfinalsmtpaddress.xlsx
# Send notification to each user in the list
Foreach ($User in $Users) {
$ToAddress = $User.PrimarySmtpAddress
$Name = $User.DisplayName
$EmailAddresses = $User.EmailAddresses
$EmailBody = @"
<p style='font-size:10.0pt;font-family:"Arial",sans-serif'>Dear $Name.<o:p></o:p></span></p>
<p style='margin-left:18.0pt;text-indent:-18.0pt;
<![if !supportLists]><span style='font-size:10.0pt;
font-family:Symbol;<span
style='·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span></span><![endif]><span style='font-size:10.0pt;font-family:"Arial",sans-serif'>The
following is a list of email addresses which are currently attached to your

mailbox.<o:p></o:p></span></p>

Email Addresses: $EmailAddresses

The list of users with multiple smtp addresses have been generated and it is in excel format with each email have been displayed follow line break like this

Problem is when I send an email to them using this function to display their email addresses Email Addresses: $EmailAddresses, all their smtp address does not display one by one with line break, it seem to combine them into one long line which make difficult for user to read. The excel spreadsheet which contains smtp addresses already got correct format 

I just wonder if anyone know how can I overcome that?

Name                                                                                                  Primary Email                                               EmailAddresses                                                                                                 

Hung Nguyen

hnnguyen@hwle.com.au

  jmarz@tresscox.com.au
  jmarz@lawsonsmith.com.au
  jmarz@abbotttout.com.au
  jmarz@hwl.com.au
  jmarz@cridlandsmb.com.au
  jmarz@hwlebsworth.com
  jmarz@hwlebsworths.com
  jmarz@hwlebsworths.com.au
  jmarz@ebsworths.com.au
  jmarz@kellyco.com.au
  jmarz@downingslegal.com.au
  jmarz@downings.com.au
  jmarz@hwlebsworth.com.au
  joseph.marz@hwle.com.au
  Joseph.Marz@hwlebsworth.com.au
  JMarz@ebsworth.com.au
  Joseph.Marz@hwl.com.au

ADAL token problem when connecting to PowerBI Service via API from powershell

$
0
0
hi, 

I'm trying to connect to powerBI by using API from powershell.

this is the code that I'm using:

$common = $PSScriptRoot + "\common.ps1"
. $common

##set parent directory for this file
#set project setting file
$parentfDir = Split-Path $PSScriptRoot -Parent 
$confDir = getFilePath $parentfDir "\json\automation_tools_seting.json"

#get project settings and package parameter
$conf = loadJsonFile $confDir

$user = $conf.PBI_user
$pass = $conf.PBI_pass | ConvertTo-SecureString -asPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential ($user, $pass)
try {
    Connect-PowerBIServiceAccount -Credential $credential

    Disconnect-PowerBIServiceAccount
}
catch {
   Write-Output "$($_.Exception.Message)"
}

but it always has an error :
Connect-PowerBIServiceAccount : Failed to get ADAL token:


wondering if there's way to fix this problem


O365 PowerShell: Find users that have specific product license services enabled

$
0
0

I'm hoping this is the right place to post this. I have posted here too but have always had better results from TechNet forums.

I'm using the following article View account license and service details with Office 365 PowerShell to try to obtain a report of all users in our tenant where the product license Office 365 Enterprise E3 is assigned but with only the the service Exchange Online (Plan 2) enabled.

The article suggests this can be done with a command similar to the following:

Get-MsolUser|Where-Object{
   $_.isLicensed -eq $true -and $_.Licenses[0].ServiceStatus[16].ProvisioningStatus-eq "Enabled"}

In my case [16] being the 17th service in the list for Office 365 Enterprise E3.

There are additional lines before to set the criteria for the rest of the services as "disabled" but hopefully you get the idea however, the article also states that the index number reflects the order that the product license and service plan appears when running either of the below script blocks:

Licenses:

Get-MsolUser-UserPrincipalName o365.test1@tenant.com  |Format-ListDisplayName,Licenses

Services:

Get-MsolUser-UserPrincipalName o365.test2@tenant.com).Licenses.ServiceStatus

The issue with the above is that many users have different combinations of plans enabled so for some, a license index of [0] would refer to a different service plan. e.g. user1 has Visio Online Plan 2 and Office 365 Enterprise E3 product licenses assigned but user2 only Office 365 Enterprise E3. Index [0] in this instance would be different making the initial script block useless in finding all users with a specific service enabled regardless of combination of product licenses assigned.

Am I missing something here?

Copy all rows grouped with powershell from an spreadsheet to another

$
0
0

Hi folks

I am trying to copy data from one sheet to another. In the first sheet i have some rows. Every visible row has grouped  folded rows.

I try to copy all rows using this code

$path = "C:\Users\john\Desktop\wb.xlsx" $Excel = New-Object -ComObject excel.application $Excel.visible = $false $Workbook = $excel.Workbooks.open($path) $Worksheet = $Workbook.WorkSheets.item(“Sheet1”) $worksheet.activate() $range = $WorkSheet.Range(“A:G”).EntireColumn $range.Copy() | out-null $Worksheet2 = $Workbook.Worksheets.item("Sheet2") $Range = $Worksheet2.Range(“A:G”) $Worksheet2.Paste($range) $workbook.Save() $Excel.Quit() Remove-Variable -Name excel [gc]::collect() [gc]::WaitForPendingFinalizers()

but executing it, only are copied the visible rows, losing the hidden folded rows, belonging to each visible row

So , please anybody suggest anyway to copy the cells including the gropped folded rows asociated to the visible cells?.

your help is much appreciated, BR.

Merge Multiples PSTs files in to one PST

$
0
0

I need to merge / combine multiples PSTs files in to one PST. I generate multiples small PST files which I would like to merge into one PST.

Thanks for any help

Powershell session for DMZ network

$
0
0

I try to connect WSUS server which is in DMZ and pull a list of computer names  with LastSyncTime.

$wsus = .\PSExec \\WSUS-SERVER -u Administrator -p Administrator Powershell

Get-WsusComputer -All | Select FullDomainName, LastSyncTime

I get the results but when exit the wsus session I lost the arrays content. I'm not sure how to edit this code to save content of $wsus?  

Installing webserver on Windows 10 Build 1803 - Powershell Script

$
0
0

Hi,

I am building a developers windows 10 machine who use .NET, Visual C++ and other softwares. They need to have IIS installed on Windows 10 machine. We have a ps script that runs to install these features on Windows Server 2016. I am trying to run this script on the Windows 10 machine. It gives me an error 

Add-WindowsFeature : The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, ...................

So, I went and tried and did a "Import-module servermanager"

and it is not able to to load the servermanager since no valid module file was found in any module directory. How can I go about getting this installed. Here is the script shown below that I am trying to run on a Windows 10 machine.




AA2913


Need to Copy all treeview nodes(which are "checked") when i hit the command button using powershell.

$
0
0

Hi,

I am not able to find direct powershell command to copy the all treeview nodes(which are "checked") when i hit the command button. kindly advice and share the script for achieving the task. thanks.

Regards,

Senthil kumar R. 

color the output if service state is stopped

$
0
0

Hi'

I have this lines:

$SPServices = Get-WmiObject -Class Win32_Service -ComputerName $ComputerName 
$SPServices | Select-Object DisplayName, StartName, StartMode, State, Status |Sort-Object DisplayName | Ft -Auto
I need that a service in state "Stopped" will be in red at the output, haw can I achieve this?

Formatting the output of the script

$
0
0

I have create a script that fetches the name of AD Object, however there are some user defined properties in the objects that requires some formatting initially I was simply loading the properties and the data was obtained in proper tabular structure.

Get-ADGroup -Filter { 'objectClass' -eq 'grp' } -Properties Name, GUID | Select Name, GUID

From the script above the data will be loaded in this format

Name             GUID

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

Test              ABCD-1234-XXXX

Test2            JKLM-4567-YYYY

I have a function that I am using to count the days let say do operation on the group after some x days. So, the count of x is fetched through that function. Say CountX(). 

So, my script is somewhat like.

$ADGROUP = Get-ADGroup -Filter { 'objectClass' -eq 'grp' } -Properties Name, GUID | Select CountX(GUID) +" - "+ Name, GUID

function CountX($ADGroup){

#SomeOperations Counting the DueDate return $DueDate #Lets Say The Date is in the format "yyyy/MM/dd" }

$ADGroup | Select-Object -Join (CountDueDate($ADGroup), Name), ObjectGUID // Concatenating Name & Date String()

But the script is causing the error :  The term 'CountDate' is not recognized as the name of a cmdlet, function, script file, or operable program. I think I am not invoking my function properly. Any Suggestions?

My Expected Output is Suppose to be:

Name                                GUID

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

2019/01/01 Test               ABCD-1234-XXXX

2019/01/01 Test2             JKLM-4567-YYYY


A specified logon session does not exist. It may already have been terminated

$
0
0

Hello, everyone! I recently meet a strange problem about double hop.

I try to run the following PowerShell command

$credential = Get-Credential

$computerName = "frxp02361Dmbssh"

$psdrive1 = @{
    Name = "PSDrive1"
    PSProvider = "FileSystem"
    Root = "\\mbssh01\Tool"
    Credential = $credential
}

$psdrive2 = @{
    Name = "PSDrive2"
    PSProvider = "FileSystem"
    Root = "\\dyn\AX"
    Credential = $credential
}

$psdrive3 = @{
    Name = "PSDrive3"
    PSProvider = "FileSystem"
    Root = "\\scmlabe3\SCM"
    Credential = $credential
}

$psdrive4 = @{
    Name = "PSDrive4"
    PSProvider = "FileSystem"
    Root = "\\codeflow\public"
    Credential = $credential
}

Invoke-Command -ComputerName $computerName -ScriptBlock {
     New-PSDrive @using:psdrive1
     New-PSDrive @using:psdrive2
     New-PSDrive @using:psdrive3
     New-PSDrive @using:psdrive4
}

Finally, I successfully create new PSDrives of "\\mbssh01\Tool", "\\scmlabe3\SCM", "\\codeflow\public"EXCEPT FOR "\\dyn\AX"

I received the following error:

Name           Used (GB)     Free (GB) Provider      Root                                CurrentLocatio PSComputerNam
                                                                                                      n e
----           ---------     --------- --------      ----                                -------------- -------------
PSDrive1                                             \\mbssh01\Tool                                     frxp02361D...
A specified logon session does not exist. It may already have been terminated+ CategoryInfo          : InvalidOperation: (PSDrive2:PSDriveInfo) [New-PSDrive], Win32Exception+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand+ PSComputerName        : frxp02361Dmbssh

PSDrive3                                             \\scmlabe3\SCM                                     frxp02361D...
PSDrive4                                             \\codeflow\public                                  frxp02361D...

We can see the command "New-PSDrive @using:psdrive2" failed.

But the other three commands all succeed.

I have tested that I can access the folder "\\dyn\AX" in File Explorer when I login into the remote computer.

Can anyone help me? I will be very grateful!




Easy way to download updates from Update Catalog using Powershell

$
0
0

Hello,

We use to download specific updates manually from Update Catalog website every month. The reason behind the process is, we need MSU or EXE files which will be used for group manual patching. Where as we weren't able to collect the same files downloaded by WSUS content, turns out they are CAB files. To reduce our load, we were trying to come up with a PowerShell script to download updates from Catalog website directly, but we are hitting on dead road. 

It would be great if someone could share their thoughts or suggestions on how to obtain the MSU or EXE files of the updates and not the CAB files.

Thanks
Senthil

Array or Hashtable?

$
0
0

Hello everyone,

Let's say I have a file somewhere with following content:

abc=1
cde=2
def=3

And I have an empty Hashtable:

$ht1 = @{}

Now, I read file content and convert it to another Hashtable, like this:

$ht2 = Get-Content -Path .\file.txt | ConvertFrom-StringData

If I try to add $ht2 to $ht1 I get following error:

PS > $ht1 += $ht2
A hash table can only be added to another hash table.
At line:1 char:1+ $ht1 += $ht2+ ~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException+ FullyQualifiedErrorId : AddHashTableToNonHashTable

Hmmm, but both objects are Hashtables, aren't they? Let's check:

PS > $ht1 | Get-Member

   TypeName: System.Collections.Hashtable
...

PS > $ht2 | Get-Member

   TypeName: System.Collections.Hashtable
...

They are... or are they? Let's check another way:

PS > $ht1.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object

PS > $ht2.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Aha! There is the difference. But the documentation for ConvertFrom-StringData cmdlet says that it "Converts a string containing one or more key and value pairs to a hash table."

I am confused, am I missing something?

So, the questions are:

What is the real object type of $ht2?
Is there an error somewhere in ConvertFrom-StringData cmdlet behavior or documentation?
How do I add contents of the file.txt to existing Hashtable after all?

Thank you!


Help with DSC

$
0
0

Hi Guru's,

I hope that someone have time and wish to explain to me concept of non node data in dsc?


Import-WdsInstallImage : An install image could not be found in the image file

$
0
0

As asked from here I ask my question on the PowerShell forum.

Hello,

The WDS server is a freshly installed Win 2019 server.

I am trying to import install images with PowerShell.

$ImagePath = 'D:\Sources\2019\install.wim'
$ImageName = (Get-WindowsImage -ImagePath $ImagePath -Index 4).ImageName
Import-WdsInstallImage -ImageGroup 'Win2019' -ImageName $ImageName -Path $ImagePath -Multicast

However I get the following error:

Import-WdsInstallImage : An install image could not be found in the image file.
At line:3 char:1+ Import-WdsInstallImage -ImageGroup 'Win2019' -ImageName $ImageName -P ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (MSFT_WdsInstallImage:root/cimv2/MSFT_WdsInstallImage) [Import-WdsInstallImage], CimException+ FullyQualifiedErrorId : 0xC111010E,Import-WdsInstallImage

The image file is NOT read-only.

And with the console it works fine.

I also installed the latest system rollup, but the behavior is the same.

I first started to display image names with Get-WindowsImage and copy/paste the name to the Import-WdsInstallImage and got the same error. That's why I was getting directly the name from the Get-WindowsImage cmdlet. But no luck, still the same error...

And while the Import-WdsInstallImage returns an error, the Import-WdsBootImage and theGet-WindowsImage cmdlets are works fine.

Does anybody see what's wrong with my code or my command lines?

By the way, I first started to display image names with Get-WindowsImage and copy/paste the name to theImport-WDSInstallImage and got the same error. That's why I was getting directly the name from the Get-WindowsImage cmdlet. But no luck, still the same error...

And while the Import-WDSInstallImage returns an error, the Import-WdsBootImage works fine.

By the way, I first started to display image names with Get-WindowsImage and copy/paste the name to theImport-WDSInstallImage and got the same error. That's why I was getting directly the name from the Get-WindowsImage cmdlet. But no luck, still the same error...

And while the Import-WDSInstallImage returns an error, the Import-WdsBootImage works fine.

NEED POWERSHELL COMMAND TO GET USER LOGON NAME AND EMAIL ID FROM SECURITY GROUP MEMBERS

$
0
0

Hi all, Good day. I have been situated to pull out User logon name and Email IDfrom AD's security group members. Here we should ignore disable member. We are using Windows server 2008 R2 Datacenter. Please help me by sharing exact PowerShell command. Your help is very valuable to me.

Thanks  

How to pass credentials for rename-computer in powershell script (.ps1)?

$
0
0

Hi all,

In the powershell script, how to give the passwords for the "-domaincredential" property with "rename-computer"?

There is no property/method like "-password"(e.g. image)

I want the script to execute silently, without having to manually enter a password that needs to be encrypted

I refer to the following links, but I'm still confused about how to write it completely in .ps1 script
https://stackoverflow.com/questions/23482389/entering-a-password-for-domaincredential-in-rename-computer-in-powershell?noredirect=1&lq=1
https://stackoverflow.com/questions/13842611/how-to-pass-credentials-to-rename-command

I wrote it as follows, but it doesn't work(I have defined $site,$number and $path)

Thank you in advance.

Remove HTML from array

$
0
0

Hi,

POSH newb here...I know just enough to steal other people's code and stitch it together. I have a script that extracts text from XML files and dumps it to a table in an HTML report. Recently the contents of the XML files changed so that the element containing the text now contains HTML in addition to the desired text content, so "This is text" is now:

<html><body><div data-format="PresentationML" data-version="2.0" class="wysiwyg"><p>This is text</p></div></body></html>

I've found several articles that have a simple RegEx, e.g.

$1 = '"<html><body><div data-format="PresentationML" data-version="2.0" class="wysiwyg"><p>This is text</p></div></body></html>"'
$1 = $1 -replace '<[^>]+>',''

That RegEx works on a single line, but if I add it to my script the resulting table is blank. Here is the working script:

<# 
Open file dialog from here: https://gallery.technet.microsoft.com/scriptcenter/GUI-popup-FileOpenDialog-babd911d
#>

#File selection dialog
$openFileDialog = New-Object windows.forms.openfiledialog   
$openFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()   
$openFileDialog.title = "Select File to Import"   
$openFileDialog.filter = "All files (*.xml)| *.XML*"   
$openFileDialog.ShowHelp = $True   
Write-Host "Select Downloaded Settings File... (see FileOpen Dialog)" -ForegroundColor Green  
$result = $openFileDialog.ShowDialog()   
$result 
if ($result -eq "OK") {    
    Write-Host "Selected Downloaded Settings File:"  -ForegroundColor Green  
    $OpenFileDialog.filename   
    Write-Host "Import Settings File Imported!" -ForegroundColor Green 
} 
else { Write-Host "Import Settings File Cancelled!" -ForegroundColor Yellow} 
#Formatting for HTML
$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 3px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 3px;padding: 3px;border-style: solid;border-color: black;}"
$a = $a + "TD{border-width: 3px;padding: 3px;border-style: solid;border-color: black;}"
$a = $a + "</style>"

#Extract content
$Record = ([xml](Get-Content $OpenFileDialog.filename)).log.record

#Remove HTML tags
#$Record =  $Record -replace  '<[^>]+>',''


#Get file creation date & assign to variable
$Created = (Get-Item $OpenFileDialog.filename).LastWriteTime.ToString('yyyy-MM-dd')

#Hashtable used to select desired elements
$props = @(
    @{n = 'Date'; e = {$_.messageInfo.messageTimestamp}; }
    @{n = 'Sender'; e = {$_.initiator.user.companyUserEmail}; }
    @{n = 'Content'; e = {$_.messageInfo.content."#cdata-section"}; }


#Generate HTML report using date as file name
$Record | Select $props | ConvertTo-Html -Head $a > ($Created + ".html"))

Any insight on how to get the RegEx working, or an alternative approach, will be deeply appreciated.

Thanks,

M-

Convert and Export JSON to CSV

$
0
0

Hello,

Hi I am trying to use PowerShell to grab  JSON data from the following website and export the values to a CSV file.

$jsonRequest=Invoke-WebRequest -Uri https://api.punkapi.com/v2/beers
$jsonRequest.Content
ConvertFrom-Json 
Export-CSV -path c:\123lasttest -NoTypeInformation

When I try to export the data to a CSV file I don't get any data.

What am I missing here / anyone done anything similar before ?

Thanks



Viewing all 21975 articles
Browse latest View live


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