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

I would like ask for the little assistance relating to POWERSHELL-Request for help

$
0
0
                                   I welcome
                                   
As a novice Administrator I would like to ask a few questions:                               
I would like to know If there are other types of configurations that can be applied by firewall iptables in GNU/linux for added security.
Whether there is the possibility to apply the Similar configuration in relation to the firewall windows?
I know that windows firewall can be circumvented But walks to me about correcting of the present state Security as also comfort.

would like to ask exists some material whether whence thanks to which I could learn how by means of NetFirewallRule in PowerShell.
I would want to ask where I could find some kind material or other source from which to I could find out how by means of NetFirewallRule perform such configurations through the PowerShell.
In the sense of in what way should to write, I mean the rules for the programs and the connections.
Besides I would like to to ask for clarification of several of additional questions with from this topic:

Namely, whether If the I possess external firewall windows type SpyShelter This the built in firewall will be automatically disconnected?
It built in firewall automatically will be disconnected?
Whether however still remains vulnerable to attack?
I also would like to ask whether they are some additional free materials/Videocasty for this type of educational platform:Udemy,Khan Academy,VirtualMicrosoftAcademy,coursera,Virtual Study.
On theme this type of administration with the participation of PowerShell'a?
 
since Recently, I learn Administration with the participation of PowerShellu However, very quickly assimilate knowledge in this topic and I would like get to know its greater opportunities because the work in him seems to be cool.
Regards.
DigitalBox.

" FullyQualifiedErrorId : AmbiguousParameterSet,Enable-RemoteMailbox"

$
0
0

Hi 

I am trying to enable remote mailbox for multiple user using CSv file input, but while running the script getting below error

Parameter set cannot be resolved using the specified named parameters.
    + CategoryInfo          : InvalidArgument: (:) [Enable-RemoteMailbox], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Enable-RemoteMailbox
    + PSComputerName        : CAS1

While I am able to enable-remotemailbox for single user w/o csv file input.

Please help..

Here is script

$Users=Import-csv -Path "D:\Input2.csv"
$Users | ForEach-Object {
Enable-RemoteMailbox -Identity $_.samaccount -Alias $_.samaccount -RemoteRoutingAddress ($_.samaccount+'@domain.mail.onmicrosoft.com') -Archive
}

In exchange hybrid mode

Thank you..


Thanks, Sunil Gupta Sunilgupta@sunilgupta.com

Foreach

$
0
0

Hello,

    Foreach can access dot properties as well? For eg:

$boxes = get-process

foreach($box in $boxes.handles) is possible? how can i access the dot properties , is there any other way?

Parsing HTML DOM

$
0
0

Hi all

I'm attempting to parse a webpage and get some data from a cell in a table.

Everything I've read thus far has some great examples, but I can't seem to get this working

$VerSite = 'https://technet.microsoft.com/en-us/windows/release-info.aspx'
$SiteData = Invoke-WebRequest -Uri $VerSite

I want to parse the OS Build 14393.222 but I suspect I need to iterate through a bunch of elements, I'm not quite sure.

Any pointers would be appreciated!

Script to send email report of time-sync (W32tm /Monitor) status for multiple domains.

$
0
0

Hi Friends,

Need your urgent help in this regard.

Looking for a automation script (Powershell) to send mail after capturing the W32tm /Monitor report for multiple domains in a forest. just targeting on DC in forest should capture the all the domains or child roots nested to it.

ex: w32tm /monitor /domain:[domain name]

Explored couple of other scripts but the readable formatting is not simple.


Script 1:

$Servers = "ntp.xxxxx,ntp.xxxxx,dc1,dc2,dc3,dca,dcb,dcc"
$ListDomains = "domain1","domain2"

Foreach ($Server in $ListServers) {
    $time = (w32tm /stripchart /dataonly /computer:$Server /samples:1)[-1].split("[")[0]
    "$Server`: `t $Time" #| out-file $timeFile -append
    $time = ""  


ForEach ($Domain in $ListDomains) {
    "** $Domain **"
    w32tm /monitor /domain:"$Domain.unisa.edu.au" /nowarn /threads:5
}

Script 2:
 $output1 = & w32tm /monitor /domain:yourdomain.com /threads:5
    $stdOutStart = 8
    $output = $output1[$stdOutStart..$output1.Length]
    $timeInfos = @()

    for ($i = 0 ; $i -lt $output.Length ; $i+=4) {
        $server = $output[$i].Split(' ')[0]
        $icmp = $output[$i+1].Trim().Split(' ')[1]
        $offset = $output[$i+2].Trim().Split(' ')[1]
        $timeInfos += New-Object PsObject -Property @{
            Server = $server
            ICMP = $icmp
            Offset = $offset
        }
    }

    $timeInfos

Script 3:

$output = & w32tm /monitor /domain:mylab.com /Threads:5
$output

Script 4:
$output = & w32tm /monitor /domain:mylab.com /threads:5
$output | Where-Object{!$_.StartsWith("Analyzing") -and !$_.StartsWith("           ") -and !$_.Contains(" of ") -and !$_.StartsWith("Stratum") -and !$_.StartsWith("delayoffset")}""


Ravi Ch

How can I get these CN values for my ADUsers?

$
0
0

Hi. I am trying to write something that extracts and selects a set of properties for my users in AD.

I want it to return the names everything I select and show the CN values of the groups and manager that are associated with them.

But what I have created so far only returns the values as long DN's.

eg : This is what I have so far, but it returns the manager and memberof values as DN's.

$searchbase = 'OU=Users,OU=home,DC=netw,DC=com'
$arrprops = ('givenname','manager','memberof')

get-aduser -SearchBase $searchbase -Filter * -Properties $arrprops | select $arrprops

Format output of invoke-command

$
0
0

Hello,

I just started learning powershell and I need a help. I wrote script which will show me partition free space on all clients servers to check if there is need to make a space:

Invoke-Command -computer (get-content C:\script\computers.txt) -ScriptBlock { Get-CimInstance win32_logicaldisk | where {$_.drivetype -eq 3} |
select -Property Name,@{n='Freespace';e={$_.freespace / 1024MB}}  

Problem is when one server has mote than 1 partition than the property PScomputername is unnecessarily repeated:

Name           : C:
Freespace      : 8,51523208618164
PSComputerName : DC01
RunspaceId     : edecc2eb-5302-4e95-91c6-543bbc66b273

Name           : D:
Freespace      : 1,79254150390625PS
PSComputerName : DC01
RunspaceId     : edecc2eb-5302-4e95-91c6-543bbc66b277

is there a way to change output to be like this:

PSComputerName : DC01
Name           : C:
Freespace      : 8,51523208618164
Name           : D:
Freespace      : 1,79254150390625PS

and still have a choice to export to it to file if needed. Thank you for any help.

need a modification to a script

$
0
0

I feel like this would be an easy thing, but some PS stuff is just beyond my immediate comprehension.

I have 3 lines of code that I apply to every user that I add to O365 to allocate a license for them. I put in each line for each user (so, 3 lines per user). I made an excel sheet out of this so at least a little monotony is relieved, but I know this could be better. I would like to know how this could be improved so that it takes input from a file (C:\temp\usernames.txt) and is just a couple of lines of PS code, rather than the mess I currently have.

Without further ado, here's the code:

 

$MyLicenseAssignmentOption = New-MsolLicenseOptions -AccountSkuId "company:ENTERPRISEPACK" -DisabledPlans EXCHANGE_S_ENTERPRISE

Set-MsolUser -UserPrincipalName email@chromalloy.com -UsageLocation US

Set-MsolUserLicense -UserPrincipalName email@chromalloy.com -AddLicenses "company:ENTERPRISEPACK"

Set-MsolUserLicense -UserPrincipalName email@chromalloy.com  -LicenseOptions $MyLicenseAssignmentOption

Your genius is appreciated.


Powershell Script to find all share in system

$
0
0

Hi Team,

I am looking for script , which can check all computers in domain and find all shares for each computer , including if C or D drive shared at root level.

Regards,

Triyambak


Regards, Triyambak

Powershell V3 - Logparser 2.2 - file path length analysis

$
0
0

I'm using logparser 2.2 to get a list of files with a path greater than 260. I can get the command line to work:

("SELECT add(strlen(path), strlen(name)) as pathlen, path, name FROM c:\downloads\*.* WHERE (pathlen > 260) order by pathlen desc" -i:fs)

I've tried putting this into a powershell script but am getting an exit code 13. along with an error of

Error: detected extra argument "add(strlen(path)," after query

The code I am using is:

$tempoutputfile = "c:\scriptresults\logparsertemp.txt" $temperrorfile = "c:\scriptresults\logparsererror.txt" $logParser = 'C:\Program Files\Log Parser 2.2\LogParser.exe' $allArgs = ("SELECT add(strlen(path), strlen(name)) as pathlen, path, name FROM c:\downloads\*.* WHERE (pathlen > 260) order by pathlen desc -i:fs -o:w3c") $ps = Start-Process -FilePath $logParser -ArgumentList $allargs -Wait -Passthru -NoNewWindow -RedirectStandardOutput $tempoutputfile -RedirectStandardError $temperrorfile; $ps.WaitForExit() # block till exe finish $ps.ExitCode;

# Thanks to JPBlanc on StackOverflow for the error trapping code

Any help with a solution greatly appreciated.  I need to be able to access the results from this code within Powershell to use in the next stage.

Regards,

Pete.

Need help to create VM's parallel using powershell

$
0
0

I am using following code to create VM's sequentially but i am not able to create VM's parallel. Please help me.

[int]$a=1
[int]$b= 101
#Copy the VHD File 
for($i=1;$i -le $a;$i++ )
{
Copy-Item 'G:\NewVHDX2012\WindowsServer2012_EPRs.vhdx' -Destination G:\EPRVMs\VM$i.vhdx

#Created a VM
New-VM –Name Win2012_$i –MemoryStartupBytes 8GB –VHDPath "G:\EPRVMs\VM$i.vhdx" -Path G:\EPRVMs\VM$i  -SwitchName 'Intel(R) 82579LM Gigabit Network Connection - Virtual Switch'
#Start the VM
Start-Sleep -Seconds 2
Start-VM -Name Win2012_$i
Start-Sleep -Seconds 2
if(( (Get-VM Win2012_$i).state -eq 'Running') -and ((Get-VM Win2012_$i).status -eq "Operating normally"))
{
Start-Sleep -Seconds 10
do
{
  
   $IPAddress=(Get-VM -Name Win2012_$i | Select -ExpandProperty NetworkAdapters | Where-Object {$_.SwitchName -like "Intel(R) 82579LM*"} |Select-Object -ExpandProperty IPAddresses -ErrorAction SilentlyContinue)
Start-Sleep -Seconds 5

}while($IPAddress -eq $Null)
}

$IPAddress=(Get-VM -Name Win2012_$i | Select -ExpandProperty NetworkAdapters | Where-Object {$_.SwitchName -like "Intel(R) 82579LM*"} |Select-Object -ExpandProperty IPAddresses -ErrorAction SilentlyContinue)[0]
Echo $IPAddress
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ -h cscript.exe "C:\Users\Administrator\Desktop\test.vbs" | Out-File c:\test.txt
$EthernetName= (Get-Content c:\test.txt | Select-Object -last 1)
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ cmd.exe /c netsh.exe interface ip set address name= "$EthernetName" static 192.168.1.$b 255.255.255.0 192.168.1.1 
$IPAddress = "192.168.1.$b"
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ -h powershell.exe "Rename-Computer -ComputerName "'$env:computername'" -NewName "Test-$b" -F"
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ -h powershell.exe Restart-Computer -F
Start-Sleep -Seconds 90
$b+=1
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ -h powershell.exe "C:\Users\Administrator\Desktop\EPRCreation.ps1" $i
Start-Sleep -Seconds 5
}


Closing an Internet explorer tab

$
0
0

Hi,

I am installing Greenshot. At the end Greenshot will open an IE Window. Is it possible shutting down this IE process and not all IE Process?

Thanks,

Starting SQL backup using custom backup location in Backup-SqlDatabase cmdlet under a specific user. How to avoid output thread running under NT SERVICE\MSSQLSERVER and avoid Operating system error 5(Access is denied.)

$
0
0

Hello,
Cloud somebody please explain how do I start backup using custom backup location in Backup-SqlDatabase cmdlet (a part of SQLPS module) under a specific user?
It feels like BackupSqlDatabase cmdlet runs backup under NT SERVICE\MSSQLSERVERaccount which might not have access to custom locations.

Here's what I get when trying to create a backup of a database and its transaction log in a temporary folder:

Code:

Function Save-BountyBackup {
$Actions = @('Database'; 'Log')
Foreach ($Action in $Actions) {
Backup-SqlDatabase -ServerInstance EHSQL -Database Bounty -BackupAction $Action -BackupContainer $env:TMP
}
}

Error:

PS SQLSERVER:\> Save-BountyBackup
Backup-SqlDatabase : System.Data.SqlClient.SqlError: Cannot open backup device
'C:\Users\Admin\AppData\Local\Temp\EHSQL-MSSQL11.MSSQLSERVER-Bounty-131196218306187834.bak'. Operating system error 5(Access is denied.).
At line:4 char:1+ Backup-SqlDatabase -ServerInstance EHSQL -Database Bounty -Back ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : InvalidOperation: (:) [Backup-SqlDatabase], SmoException    + FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.BackupSqlDatabaseCommand

Backup-SqlDatabase : System.Data.SqlClient.SqlError: Cannot open backup device
'C:\Users\Admin\AppData\Local\Temp\EHSQL-MSSQL11.MSSQLSERVER-Bounty-131196218307533759.log'. Operating system error 5(Access is denied.).
At line:4 char:1
+ Backup-SqlDatabase -ServerInstance EHSQL -Database Bounty -Back ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : InvalidOperation: (:) [Backup-SqlDatabase], SmoException    + FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.BackupSqlDatabaseCommand

 

However, if I specify the default folder specified in SQL, or any folder underneath, the script works fine.
Code:

Function Save-BountyBackup {
$Actions = @('Database'; 'Log')
Foreach ($Action in $Actions) {
Backup-SqlDatabase -ServerInstance EHSQL -Database Bounty -BackupAction $Action -BackupContainer .\Defect\
}
}

The default SQL Backup location used by BackupSqlDatabase cmdlet is: $ENV:ProgramFiles\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup


How do I make this cmdlet to output backup to a custom location without having to add the NT SERVICE\MSSQLSERVER user to the ACL of the destination?

 I am sure the user used to run Windows PowerShell ISE has the same write permissions to any folder on this PC as it has to the$ENV:ProgramFiles\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup location andI don't want to add NT SERVICE\MSSQLSERVER to the ACL of this custom backup location.

Access permissions on the default backup location:

PS SQLSERVER:\> (Get-Acl "$ENV:ProgramFiles\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup").access | Format-Table
FileSystemRights AccessControlType IdentityReference      IsInherited                InheritanceFlags PropagationFlags
---------------- ----------------- -----------------      -----------                ---------------- ----------------     FullControl             Allow CREATOR OWNER                False ContainerInherit, ObjectInherit      InheritOnly     FullControl             Allow NT AUTHORITY\SYSTEM          False ContainerInherit, ObjectInherit             None     FullControl             Allow BUILTIN\Administrators       False ContainerInherit, ObjectInherit             None     FullControl             Allow EHSQL\Admin              False ContainerInherit, ObjectInherit             None     FullControl             Allow NT SERVICE\MSSQLSERVER       False ContainerInherit, ObjectInherit             None

Access permissions on the custom backup location:
PS SQLSERVER:\> (Get-Acl "$ENV:TMP").access | Format-Table
FileSystemRights AccessControlType IdentityReference      IsInherited                InheritanceFlags PropagationFlags
---------------- ----------------- -----------------      -----------                ---------------- ----------------     FullControl             Allow NT AUTHORITY\SYSTEM           True ContainerInherit, ObjectInherit             None     FullControl             Allow BUILTIN\Administrators        True ContainerInherit, ObjectInherit             None     FullControl             Allow EHSQL\Admin               True ContainerInherit, ObjectInherit             None

Thank you.


Well this is the world we live in And these are the hands we're given...

Reference .Net .dll from powershell script

$
0
0

Could you please help me in referencing .Net .dll from powershell script? I'm using powershell ISE to write/debug script. I've some .net code which is referencing Nuget package in it and I want to embedded that code in powershell script.

It works well if I do copy required .dlls in C:\WINDOWS\system32\WindowsPowerShell\v1.0 and script's root(C:\TestProjects\UpdateLocalNugetRepository) path. I don't want to do that beacuse in production we can not copy .dlls to system32 folder.I know that I'm doing something wrong. Could you please help?

Below is my powershell script - 

$path = "C:\TestProjects\UpdateLocalNugetRepository"

$Assem =@(
        "$path\NuGet.Configuration.dll","$path\System.Core.dll","$path\System.dll"
         )


$Source = @”
using NuGet.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace NuGetPSTest
{
    public class Utility
    {
 	public static async Task<bool> MyMethod(string packageName, string p1, string p2)
        {
       		//Here I use above mentioned .dll(Nuget.Configuration).
	}
    }


}

“@

Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp



$result = [NuGetPSTest.Utility]::MyMethod(param1,param2,param3).GetAwaiter().GetResult()
$result

Thanks in advance.






Tutorial Series for using Power Shell for mail chimp.

$
0
0
I am trying to make a power shell script for using mail chimp. I am some what of a newbie. It seems I would mostly use HTTP Post/Get/Patch calls to talk to the Mail Chimp API v3. Still I'm a bit lost with powershell, and was wondering if anyone can point me to a tutorial that has Powershell calling to Mail Server APIs...

Datagrid reverts to unfiltered list when header clicked

$
0
0

Hi everyone,

Just looking for advice, what's a good way to deal with the datagrid list reverting back to its unfiltered list when the header is clicked.

I have example code here:

https://codeshare.io/zbPcS

I have tried to keep the code as short as possible to just show the issue. I have a txtbox acting as a filter.

If i type for example svc in the filter and click the button it lists all processes that match the filter. This works fine.

If I then click the header of the datagrid I get the unfiltered list again.

I have been doing this to work around the problem:

$Customdata = New-Object -TypeName System.Collections.ObjectModel.ObservableCollection[object]


    $view | ForEach-Object -Process {
        $Customdata.Add((
                New-Object -TypeName PSObject -Property @{
                    Name         = $_.Name
                }
        ))      

But there must be a much easier cleaner way of doing this. Thanks in advance !

Content Length

$
0
0

following script work exactly what i want but not getting full Content,   it has some fixed length, because of this, unable to get full Content,

is there a way i can define length of content to MAX size

$splat=@{
    Uri="https://xxxxx/Dictionary/AcaActions"

    Header =@{"ContentType"="text/xml";"oToken"= "323213131"}

Invoke-WebRequest @splat | Out-file "C:\Temp\api3.txt"

even i tried with ContentType = application/json

Thanks

V

    

Login Script

$
0
0

Well I've looked and looked and haven't found anything quiet like what I'm needing to do so here goes.

I have a student domain that we must restrict students access to the computer and internet as much as possible. Since I'm not scripting/programing challenged I'm in hopes someone can give me a leg up on how to use Power Shell to do a login task for student sign ins.

I have a default.htm file with specific URLs and aps the students can access while on the computers. This default.htm file resides on my domain controller but I need a script that when the students login the .htm file will be copied down to the local machine to, say the C:\public\public documents folder where the GPO points IE 11 to go to for the default browser page.

Sure will appreciate any help I can get in accomplishing this task soon.

Thanks in advance!

How to get all the modules that can be used in windows server 2012 R2 when i haven't imported or installed them before.

$
0
0

Hello there, 

my problem is, I need to see the names of all the modules in windows server 2012 R2. However, when i use the Get-Module -ListAvailable cmdlet, it doesn't list all the possible modules. It only lists those modules that are already installed.

For instance, i don't have ADDS installed, so when i request for the available modules, its not listed. What i need is a way of seeing the names of all the "possible Modules" whether installed or not.

If this is possible, how do i achieve it?

Thanks

Cheers

paul Gonzaga

MCSA Student

Convert all files end line char from a folder to another(win,mac,unix) and place in same or another folder

$
0
0

Hi All,

Below script is used to convert file end line char to passed format like unix, win, mac.

But i want this to fetch all files one by one from passed folder name and replace end line char.

Param(
  [Parameter(Mandatory=$True,Position=1)]
    [ValidateSet("mac","unix","win")] 
    [string]$lineEnding,
  [Parameter(Mandatory=$True)]
    [string]$FolderPath
)


foreach ($file in (Get-ChildItem $FolderPath))
{
    

    # Convert the friendly name into a PowerShell EOL character
    Switch ($lineEnding) {
      "mac"  { $eol="`r" }
      "unix" { $eol="`n" }
      "win"  { $eol="`r`n" }
    } 

    # Replace CR+LF with LF
    $text = [IO.File]::ReadAllText($file) -replace "`r`n", "`n"
    [IO.File]::WriteAllText($file, $text)

    # Replace CR with LF
    $text = [IO.File]::ReadAllText($file) -replace "`r", "`n"
    [IO.File]::WriteAllText($file, $text)

    #  At this point all line-endings should be LF.

    # Replace LF with intended EOL char
    if ($eol -ne "`n") {
      $text = [IO.File]::ReadAllText($file) -replace "`n", $eol
      [IO.File]::WriteAllText($file, $text)
    }    
}
Echo "   ** Completed **" 

Thanks in advance..

Viewing all 21975 articles
Browse latest View live


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