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

Powershell - Extract contents between sections in word doc

$
0
0

We have successfully extracted contents from word doc using PowerShell for search terms.

But now we have to extract a particular section from Word document. Extract 30.5 complete section (points a (i and ii) and b (i and ii) needs to be extracted).

30.5    Team Structure for BI Project
(a) 2 teams will be created for the project:
(i) Database Professionals will be responsible for backend;
(ii) Quality assurance professionals will be responsible for quality;

(b) Following environments will be provided
(i) Virtual Machine will be provided to all developers
(ii) Separate sever will be created for Quality assurance team

30.6    Process of Deployment

Following piece of code we have used in past, but how to extract complete section:

Get-Content $SourceFileName |Select-String-Pattern $keyword  

$F =Select-String-Path"seach.doc"-Pattern"Team Structure for BI Project"-Context0,10
Issue with above code is that I don't how much data will be there in one section. In this I have to extract everything in section 30.5

Turn Off Unwanted Variable Expansion?

$
0
0

In both the ISE and console, when trying to assign a path variable, $HOME is auto-expanding. I start to type:

$Table | Export-Csv -Path "$HOME\


and then attempt to use tab completion and select, say 'Desktop':

The result is:

$Table | Export-Csv -Path "C:\Users\keith\Desktop"

But what I want is:

$Table | Export-Csv -Path "$HOME\Desktop"

So PowerShell is being a little too helpful. Any way to turn this off?

Keith


Keith

Powershell WCF and Multiple Bindings

$
0
0

Hi everyone,

I think my terminology may be incorrect. But searching around the web I am not 100% sure on what I am asking for.

I am integrating into a WCF WSDL interface with <g class="gr_ gr_10 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="10" id="10">powershell</g>.

I am trying to access a method called "CreateUser" However the method exposed in the main interface (2012) is limited. I am trying to access the 2014 interface like I do in SoapUI but it seems Powershell's intelisense is stuck on the 2012 version of the WSDL. Anyone know how to reach the other part of the WSDL so PowerShell can access the 2014 version call method? Is it a different "Binding" as SoapUI calls it or a different "Namespace" or is it just not possible with using New-WebServerProxy?

Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host #$where = 'https:///Interconnect-REL-EDI/wcf/Epic.Security.GeneratedServices/PersonnelManagement.svc?wsdl'#$where = 'https://../Interconnect-REL-EDI/wcf/Epic.Security.GeneratedServices/PersonnelManagement.svc?wsdl'#$where = 'https://../Interconnect-REL-EDI/wcf/Epic.Security.GeneratedServices/PersonnelManagement.svc?wsdl=wsdl2'#$where = 'https://../Interconnect-REL-EDI/wcf/Epic.Security.GeneratedServices/PersonnelManagement.svc/basic_2014?wsdl'$where = 'https://../Interconnect-REL-EDI/wcf/Epic.Security.GeneratedServices/PersonnelManagement.svc?singleWsdl?wsdl' $ws = New-WebServiceProxy -uri $where -UseDefaultCredential -Namespace "Services.PersonnelManagement" -Class "urn:Epic-com:Security.2012.Services.PersonnelManagement"

$ws

$namespace = $ws.getType().namespace

Write-Host $namespace

$ws.GetType().class[IPersonnelManagement2014.PersonnelManagementCreateUserResponse] $response$ws.CreateUserexit





Need to read text file as an array and get elements from each line of array using Powershell

$
0
0

Hello,

I'm trying to read in a text file in a Powershell script.  The text file name is Database.txt and for this example it contains two lines as seen below:

Database.txt contents:

one,two,three,four
five,six,seven,eight

I need to read each line of the text file and assign each element of each line to a variable for further processing.  This code snipit below shows what I'm trying to do:

$DB = Get-Content C:\scripts\Database.txt
 foreach ($Data in $DB)
 {
 $First = $Data[0]
 $Second = $Data[1]
 $Third = $Data[2]
 $Fourth = $Data[3]
 
 write-host "First is: "$First
 write-host "Second is: "$Second
 write-host "Third is: "$Third
 write-host "Fourth is: "$Fourth
 Write-Host ""
 }

This code does not return the needed results.  The results it returns is this:

First is:  o
Second is:  n
Third is:  e
Fourth is:  ,

First is:  f
Second is:  i
Third is:  v
Fourth is:  e

I need it to return this instead:

First is:  one
Second is:  two
Third is:  three
Fourth is:  four

First is:  five
Second is:  six
Third is:  seven
Fourth is:  eight

I'm missing something and have tried other variations but so far I cannot get the needed results.  Does anyone know how to get the results I'm look for?  Thank you!

How to exclude Organizational Units in Get-ADComputer cmd-let?

$
0
0

Hi! 

I'm doing an Active Directory Computer query like the following:

Get-ADComputer -SearchBase "DC=mydomain,DC=com"-Filter {OperatingSystem -NotLike "*Windows Server*"}

But I try to exclude some Organizational Units in the result query. What would be the best way to do it?

Thanks in advance!

Bulk attribute change

$
0
0

I need to run below command for bulk users based on an input text file containing SAMAccountName

Set-ADUser -Identity "xyz"-Clear "extensionAttribute15

for some reason get-content is not working for me.

Unable to set printer color as b\w using power shell

$
0
0

Set-PrintConfiguration -ComputerName PrinterServer -PrinterName 'Canon5235' -Color 0 -DuplexingMode 'OneSided'

Using the above script I could change the page settings however I'm not able to change the color is there any other way to do so.

uninstall chrome by script in GPO

$
0
0

Hi guys, 

i need to uninstall google chrome on my 700 computers. 

Google chrome was installed by several different msi. So i have a lot of different chrome version on the computers. 

So i would like to use a script to uninstall all the google chrome, even the last version.

I used this powershell script : 

#Following steps are being used to uninstall the current version of Google Chrome

Write-host "Un-Installing the current version of Google Chrome from your machine..." 

$AppInfo = Get-WmiObject Win32_Product -Filter "Name Like 'Google Chrome'"

If ($AppInfo) 
{
    & ${env:WINDIR}\System32\msiexec /x $AppInfo.IdentifyingNumber /Quiet /Passive /NoRestart
}

$Reg32Key = Get-ItemProperty -path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome" -name "Version" -ErrorAction SilentlyContinue

$Ver32Path = $Reg32Key.Version

If ($Ver32Path) 
{
    & ${env:ProgramFiles}\Google\Chrome\Application\$Ver32Path\Installer\setup.exe --uninstall --multi-install --chrome --system-level --force-uninstall
}

$Reg64Key = Get-ItemProperty -path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome' -name "Version" -ErrorAction SilentlyContinue

$Ver64Path = $Reg64Key.Version

If ($Ver64Path) 
{
    & ${env:ProgramFiles(x86)}\Google\Chrome\Application\$Ver64Path\Installer\setup.exe --uninstall --multi-install --chrome --system-level --force-uninstall
}

But if it works in local on my computer (win7), it unfortunatly doesn't work on the 700 computers when i deploy this script by GPO.

Does anyone has an idea why? or an another idea to uninstall chrome (version 60 to 67) on my 700 computers.

Thanks!





Export-CSV Question

$
0
0

Hello All,

I'm trying to export a license of user licenses in office 365 before removing them. However, no matter which way I try to export it, it's not working for me.

I'm trying to make an array to export to a CSV for logging purposes. The line called "Licenses" will not export correctly. Any assistance would be greatly appreciated. 

Snippet of my script: 
    
$Date = Get-Date -uformat "%m-%d-%Y"
$RPW = (ConvertTo-SecureString (-Join ((((40..90) | Get-Random -Count 32 | % {[char]$_}) + ((91..122) | Get-Random -Count 32 | % {[char]$_})) | Get-Random -Count 12)) -AsPlainText -Force) #John Seals Contributed

Set-Location C:\Scripts

##########################
#Pull O365 Licensing Info#
##########################

Write-Host "Pulling Licensing Data" -ForegroundColor White -BackgroundColor Black
$MSolUser = Get-MsolUser -All | Where-Object {$_.IsLicensed -eq $true -and $_.BlockCredential -eq $true} | Select-Object UserPrincipalName, BlockCredential
Write-Host "Licensing Data Complete" -ForegroundColor Green -BackgroundColor Black

##########################
#Import O365 Data into AD#
##########################

ForEach ($U1 in $MSolUser){

$UPN = $U1."UserPrincipalName"
$SAM = $UPN.Split("@")[0]

$ADInfo = Get-ADUser $SAM -Properties *


#####################################
#Ignores LOA Accounts by Description#
#####################################

If ($ADInfo.Description -like "*LOA*") {Get-ADUser $SAM -Properties description | Select-Object GivenName,Surname,SamAccountName,Description| Export-Csv $PSScriptRoot\$Date-LOAUsers.csv -Append -NoTypeInformation}

Else{

 

    $Array = @{
    "First Name" = $ADINFO."GivenName""Last Name" = $ADINFO."SurName""SamAccountName" = $ADINFO."SamAccountName""UPN" = $U1."UserPrincipalName""Licensed" = $U1."IsLicensed""AD Enabled" = $ADINFO."Enabled""AD Ext 11" = $ADINFO."extensionattribute11""Cloud Blocked Credential" = $U1."BlockCredential""Description" = $ADInfo."Description" "Licenses" = $U1.Licenses.AccountSkuID -join ','
          }

    

New-Object PsObject -Property $Array | Sort-Object "First Name", "Last Name","SamAccountName", "UPN", "Licensed", "AD Enabled", "AD Ext 11", "Cloud Blocked Credential","Licenses", "Description"  | `
Select-Object "First Name", "Last Name", "SamAccountName", "UPN", "Licensed", "AD Enabled", "AD Ext 11", "Cloud Blocked Credential","Licenses", "Description"  | `
Export-Csv -Path "C:\Scripts\$Date-DisUsersLicense.csv" -Append -NoTypeInformation #MADE A CHANGE ON THIS LINE



Programmatically left clicking a tray icon.

$
0
0
I have an icon in my windows tray and i was wondering if I could write a script to left click on the icon when it was run. I don't know how to program in powershell and could honestly use some help.

Regex for search keyword in powershell

$
0
0

Following keyword need to be searched on document using powershell

["Allowed Acquisition Clean-Up Period"

$keyword =""Get-Content $SourceFileName|
        select-string -pattern $keyword

String which im searching for has double quotes in it, so i'm struggling how to mention in this $keyword

Extract text/lines between two keywords in Word Doc using powershell

$
0
0
Below code works fine, and returns me the line/text between two searched keywords

    Clear-Host
    $SearchKeyword1 = 'keyword1'
    $SearchKeyword2 = 'keyword1'
    $F = Get-Content "D:\Contract.doc"| select-string -pattern $SearchKeyword1
    Write-host $F.LineNumber
    $G = Get-Content "D:\Contract.doc"| select-string -pattern $SearchKeyword2
    Write-host $G.LineNumber
    $Z = Get-Content "D:\Contract.doc"| select-string -pattern $SearchKeyword1 -Context 0, ($G.LineNumber - $F.LineNumber - 1)
    Write-host $Z

How can we achieve the same using -COMObject model as above only works with txt but gives issues with docx word files

    $word = New-Object -ComObject Word.Application
    $word.Visible = $true
    $doc = $word.Documents.Open($file, $ConfirmConversions, $ReadOnly)
    $range = $doc.Content

Global Variables and Incremental Variables

$
0
0
Hey All,
I have started out in powershell and am trying to port a script from ksh across to PS.

I have hit a few little problems.

here is a sample of my code below
-->
[int] $global:a = 0
[int] $global:y = 0

function inc ()
{
$y++
$a = $a + 1
echo "func 1"
Write-Host $a
Write-Host $y
}
function inc_2()
{
echo "func 2"
Write-Host $a
Write-Host $y
}

inc   
inc_2
$a++
$y++
inc
inc_2
-->

Now I would expect a global variable to be caried into each function, but unfortunately it is not.

here is the output.
-->
func 1
1
1
func 2
0
0
func 1
2
2
func 2
1
1
-->

As you can see, It start the count for the variable $a,$y again for each function. Another thing i have noticed is how difficult it is to make a count function for variables. if anyone has any solutions to this. I would much appreciate it.

Thanks in Advance,

Rob.

convert .eml to .msg

$
0
0

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

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

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

PS: Dont want to use third party converters.

To convert Reg_binary to Date

$
0
0

Hello!

I am trying to get the Last Scan Date of ForeFront Endpoint Protection from the registry using power shell. Below is the command that I run to get the LastScanRun:

Get-ItemProperty "HKLM:\Software\Microsoft\Microsoft Antimalware\Scan" | Select-Object -ExpandProperty LastScanRun

Output:

243 161 69 205 157 235 207 1

I want to know if how am I going to convert the output to a date format "mm/dd/yyyy" using powershell as I dont really have an idea to convert this one. 

Your help is really appreciated. Thank you in advance.


Get File Info

$
0
0

I'm trying to create a script that will read through a folder and provide the files creation date.

I have the following.

$folder = "C:\test"

Get-ChildItem $folder | foreach {
 
  Select-Object -ExpandProperty CreationTime | 
  Get-Date -f "yyyy-MM-dd hh:mm"
}

Spits out nothing as an output though.

Any help is appreciated.

Thanks!

Powershell output the text string with new line

$
0
0

Hi,

   When I am trying to output the query result text into a text file or just display.  The result text is one long string with new line characters. I want to display the result in multiple lines (end/start with new line). Here is an example

The content of the text string is like this (in Notepad it is displayed in one single line, | is represening the new line which can not be displayed here the same way in Notepad).

Replace view DB_TESTDBV.MLR_XWALK  as Lock Row For Access  | Select COL_ID  |,COL_DSC  |,LAST_UPDT_TS  |From DB_BASEDBV.MLR_XWALK;

     I 'd like the text be displayed or output to text file like below (multiple lines).

Replace view DB_TESTDBV.MLR_XWALK  as Lock Row For Access
Select MLR_ID
,SNPSHT_EFF_YR
,MLR_DSC
,ETL_BATCH_SK
,LAST_UPDT_TS
 From DB_BASEDBV.MLR_XWALK;

   Because of the new line characters in the text result (0D ), when I use the following command to display the result from the DB query,

$dataset.Tables | Select-Object -Expand Rows

   I could only see the first one line  with "..." appending to the end

 Replace view DB_TESTDBV.MLR_XWALK  as Lock Row For Access  ...

   When I just fill this text to a string variable $testString and use Write-Host $testString, I could only see the last section displayed. I would expect to see the whole text. I even tried Here-string.

   From DB_BASEDBV.MLR_XWALK;

    Could some one help?

    Thank you!

Carol


Carol

Set Custom Attribute with Manager SamAccountName using Set-Aduser

$
0
0

Having a little trouble wrapping my brain around what should be rather simple ...

I have several hundred AD user objects.   Currently, the Manager field is populated.    What would be the simplest way to copy the SamAccount name of the Manager that is in the Manager field to a preexisting blank CustomAttribute field named extensionAttribute2 ?

Thanks so much for any  help... 

Users Manager, recorded on Manager - the manager's SamAccountName copied to Custom Attribute.

I got the 1 step process figured out "Set-ADUser -Identity "jsmith" -Replace @{ExtensionAttribute2=$True}" but I can't get the variable in there.  Thoughts?


Creating DNS zone with Powershell

$
0
0

Hi,

I have to build a script to be abble to create DNS Zone and associated records on 2 Windows server 2016. My DNS severs have to work as Name Servers for Public DNS entry

For now I'm abble to create the zone and the records from data in an Excel Sheet but I can't define "Name Servers" and "SOA" on the zone properties. When I create the zone it's created with default value like the local server name as Primary server and Name Server.

I tried to modify text file .DNS  located on "C:\Windows\System32\dns" and I'm abble to do it with prowershell but as soon as I reload the zone my change in the file disapears.

For exemple, the file created with default settings :

@                       IN  SOA dcsvp-dnsext-01.xxxxxxx.xx. hostmaster.xxxxxx.xx. (
                       3            ; serial number
                       900          ; refresh
                       600          ; retry
                       86400        ; expire
                       3600       ) ; default TTL

;
;  Zone NS records
;

@                       NSdcsvp-dnsext-01.xxxxxxx.xx.

;
;  Zone records

And the file after I changed values with Powershell :


@                       IN  SOA ns1.xxxxxx.xx. IT-Infrastructure@xxxxxx.xx. (
                       1            ; serial number
                       900          ; refresh
                       600          ; retry
                       86400        ; expire
                       3600       ) ; default TTL

;
;  Zone NS records
;

@                       NSns1.xxxxx.xx.
ns1.xxxxxx.xx.          A176.65.78.103
@                       NSns2.xxxxxx.xx.
ns2.xxxxxx.xx.          A52.136.246.68

Perhaps I don't use the correct method to achieve my goal but after a few days scripting for that I'm a bit lost and would appreciate any help or advice ....

to resume the scope, I have to create DNS zone with différents types of records on 2 Windows Server 2016 DNS servers from data in a Excel Sheet and I'm stuck at editing Zone properties for "SOA" and "Name Servers"

Enable-PSRemoting Not Working - Access Denied

$
0
0

I'm attempting to enable PS Remoting via Group policy settings https://www.techrepublic.com/article/how-to-enable-powershell-remoting-via-group-policy/ I have the steps in the document accounted for yet I'm still getting Access Denied when trying to enter-pssession. 

PS C:\WINDOWS\system32> Enter-PSSession -ComputerName "COMPUTERNAME"
Enter-PSSession : Connecting to remote server COMPUTERNAME failed with the following error message : Access is 
denied. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName "COMPUTERNAME"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (COMPUTERNAME:String) [Enter-PSSession], PSRemotingTransportExcepti 
   on
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

When I go to enable-psremoting on the machine it looks as if something wasn't accounted for in the GPO 

Do you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): a
WinRM is already set up to receive requests on this computer.
WinRM is already set up for remote management on this computer.

Confirm
Are you sure you want to perform this action?
Performing the operation "Set-PSSessionConfiguration" on target "Name: microsoft.powershell SDDL:
O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD). This lets selected users remotely run Windows
PowerShell commands on this computer.".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): a

Not sure what I'm missing here - I'd appreciate an assist! 

Viewing all 21975 articles
Browse latest View live


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