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

Getting .Net Framework version of a DLL using Powershell

$
0
0

Hi All,

      I need to get the .Net Framework version of a DLL using Powershell. 

      I need TargetFrameworkVersion not Runtimeversion.

      kindly help me to get scripts.




DSC not accepting data

$
0
0

Hi All,

I am configuring DSC to install RDS but somehow the DSC not accepting value from configuration data.

In my configuration data I have fields

$data = @{


  AllNodes = @(


    @{

        NodeName                    = '*'
        PSDscAllowPlainTextPassword = $true
        PSDscAllowDomainUser        = $true

    },

    @{

but when I run the code I get this error. Even If I have both PSDscAllowPlainTextPassword, PSDscAllowDomainUser it is not accepting it. 

ConvertTo-MOFInstance : System.InvalidOperationException error processing property 'PsDscRunAsCredential' OF TYPE 'xRDSessionDeployment': Converting and storing encrypted passwords as plain text is not recommended. For m
ore information on securing credentials in MOF file, please refer to MSDN blog: https://go.microsoft.com/fwlink/?LinkId=393729
At C:\RDS2016.ps1:109 char:9
WARNING: It is not recommended to use domain credential for node 'System.Collections.Hashtable'. In order to suppress the warning, you can add a property named 'PSDscAllowDomainUser' with a value of $true to your DSC conf
iguration data for node 'System.Collections.Hashtable'.


creating a iis certificate in powerhsell

$
0
0

In IIS 8.5 on windows server 2012r2 in my lab. I can create a selfsigned certificate by opening IIS and selecting Server certificates - Create Self-Signed Certificate.

How would i create this in Powershell by using new-selfsignedcertificate, to get the excact same properties?

I seem to be getting key usage as critical every time i run the basic new-serlfsignedcertificate :

New-SelfSignedCertificate -DnsName iis.contoso.com,myweb.contoso.com -CertStoreLocation Cert:\LocalMachine\my

any tips are welcome

NetworkAdapter not setting?

$
0
0

Hi All

I've created the below script - everything works as expected bar the last line. No failure appears it just simply doesn't seem to recognise the command.

When i run this command manually or in a script on its own it recognises it without issue.

Any ideas?

Thank you


$vCenter = "xxxxxx.xxx.xxxxx.com"
$vCenterUser = "Testing.Account"
$vCenterPassword =  "XXXXXXX"

Connect-VIServer -server $vCenter -user $vCenterUser -password $vCenterPassword

$vms = Import-Csv "C:\Scripts\VMRollOut.csv"

#set VM variables
foreach ($vm in $vms){
$VMName = $vm.Name
$Cluster = $vm.Cluster
$ESXHost = Get-VMHost $vm.ESXHost 
$ESXDatastore = Get-Datastore $vm.Datastore
$NoCPU = $vm.NoCPU
$MBRAM = $vm.MBRAM
$DiskFormat = $vm.DiskFormat
$GBDisk = $vm.GBDisk
$GuestOS = $vm.GuestOS


#VM build
New-VM -Name $VMName -VMHost $ESXHost -Datastore $ESXDatastore -NumCpu $NoCPU -MemoryMB $MBRAM -DiskStorageFormat $DiskFormat -DiskGB $GBDisk -GuestId $GuestOS 

#set the NIC
New-NetworkAdapter -VM $VMName -NetworkName "VLAN214" -type Vmxnet3
}

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.

Update the DistinguishedName using Powershell

$
0
0

Hi 

I am trying to update the DistinguishedName  but its not happening Can anyone help me to update the DistinguishedName.

Set-ADuser "usename" -DistinguishedName  "......................................."

Issue when retrieving ADUser Object remotely

$
0
0

Hi,

I have an issue in these lines :

Invoke-Command -Session $ADSession -ScriptBlock{
    param(
      [Parameter(Mandatory, Position = 0)]
      [string]$UserUPN
    )
    $ADUser = Get-ADUser -Filter "UserPrincipalName -like '$UserUPN'" -SearchScope Subtree
   } -ArgumentList $UserUPN 

If I type the Get-ADUser interactively in the session and stores it in a variable, I have what I expected : An ADUser object. But if I do the same remotely, the result is a string containing the CN.

Do you have any idea ?


The key of learning is practice.


Removal of secondayary proxyAddress/Domain issue with Set-ADuser

$
0
0

Hi,

I'm trying to remove an old domain/proxyaddress from all AD objects so I can then remove it from our O365 Tenant.

However I'm having a hard time in being able to write a PS that will do it in bulk.


If I run the below against a single user it works fine:

Get-ADUser user-propproxyaddresses|% {

$pr=$_.proxyaddresses-like"*@domain*"

Set-ADUser$_-Remove @{proxyaddresses=$pr}

}

However its against 3000+ objects so I really don't want to have manually run it against everything so I'm trying to get a bulk search/removal script but it's just not playing nice. I'm sure I'm just being stupid and missing something simple, but would really appreciate if someone could help me out.


$Users=Get-ADuser -Filter*-SearchBase"OU"

Foreach($Userin$Users){

   Get-ADUser$User–propproxyaddresses|% {

   $pr= $_.proxyaddresses -like"*@domain*"

   Set-ADUser$_-Remove @{proxyaddresses=$pr}

    }

}

But it throws the below error:

Set-ADUser : Cannot validate argument on parameter 'Remove'. The argument collection is empty.

At line:5 char:27

+     Set-ADUser $_ -Remove @{proxyaddresses=$pr}

+                           ~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADUser

Thanks again


Assigning a timeout to invoke-command

$
0
0

My script looks like:

$my_return_code = invoke-Command -Session $my_session -ScriptBlock {
        param(
        $my_arg1,
        $my_arg2)
        #
        Get-ChildItem c:\ *.* -Recurse | select name > c:\myfolder\file1.txt
        #
        } -Args $my_arg1, $my_arg2

The scriptblock takes usually 300 seconds to complete.

I need to assign a timeout so that it stops after 30 seconds even if file1.txt is not complete.

How can I assign a timeout?

Regards

Mario

Logon Script Powershell -Printing

$
0
0

Hello,

I our school district, we have the staff which works in more than one schools. Since that staff can be only in the OU of one of the schools, so that staff is pulling the printers for that school only. The printers are deployed using GP. 

In order to handle it, what I have done is that: 

I have written the powershell script which will take in csv file with names of all the staff who works at more than one school and the names of the schools they work at. The powershell script will run as logon script and since it runs the users pull the respective printers from all the schools they work at.

The problem is that some of the printers not everyone can print to. They are network printers but only admin staff is allowed to print not the teachers. But when the logon script runs it tries to add those printers too and hence it cant connect and user see that prompt box of "Connecting to the Printer". 

I was wondering if I could perform a check before adding the printers that if security permission are set to "everyone" can print then only add that printer. But I can't find a way to find out that. I was thinking of reading the security permission on the printers and then adding it.

Can anyone help?

Thanks, 
Aman

Removing Disabled Users from Groups

$
0
0

Looking for a powershell script that will remove ALL disabled users from any groups (Distribution and Security) in a particular OU.

Any help would be appreciated....


Brian Modlin

How to write a script to update AD Attribute " otherTelephone " with CSV file?

$
0
0

I have a CSV file contains the information below. I just take a few of examples.

EMPLOYEEIDWORKLANDLINE
138+1 (512) 7284071
147+1 (512) 7287269
182+1 (512) 7285688
187+1 (512) 7283613
202+1 (512) 5132257
233+1 (512) 7285549
235+1 (512) 7288711
259+1 (512) 7283881
264+1 (512) 7283684

Where " WORKLANDLINE " going to update at AD Attribute " otherTelephone "

But all these data including 4 different domains. So should I ask user to create 4 different CSV file for different domain?


Remote operation privileges

$
0
0

Hello,

I sometimes face this issue when trying to do remote operation via Powershell.

 D:\scripts\lm> get-service -ComputerName krycsmii0001 -Name bigf* | restart-service
get-service : Cannot open Service Control Manager on computer 'krycsmii0001'. This operation might require other
privileges.
At line:1 char:1+ get-service -ComputerName krycsmii0001 -Name bigf* | restart-service+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Get-Service], InvalidOperationException+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand

However Im doing this from a machine where I am logged with domain account and this account is also member of Administrators group on target servers.

what might be wrong pls?

Thanks


--------------------- Leos

Powershell in windows service not able to get results from WMI objects

$
0
0

We have a windows service which is running under a account that is not part of local admin. With in the service we call a powershell file using processstartinfo. With in powershell file we call the WMI class

"$AVGCPU = Get-WmiObject  win32_processor | Measure-Object -property LoadPercentage -Average | Select-object -expand Average"

The above code always returns 0. When i make the user as local admin then the cpu usage value is returned. Also when i run the same code in powershell launched under the same user account (without giving local admin privileges), i am able to get the value for CPU usage. Its only when the cmdlets is called from windows service i am getting this problem. Due to security restriction, i cannot make the user as local administrator. Any idea what rights should be given to the user that WMI class return value when called from windows service. Service is running in windows 2008 R2 server 

Replace first occurrence string log file

$
0
0

I trying to search a log file for the first occurrence of a string “10.2.91.52” and replace it with “localhost” This is what I got so far; however, it replaces the string but it also removes the rest of the content. Appreciate your help.

$filename = "C:\access_combined.log"

$content = Get-Content $filename | select-string "10.2.91.52"

$linenumber = $content[0].LineNumber #-creplace $match,$replacement
$linenumber

$content |
  ForEach-Object { if ($_.LineNumber -eq $linenumber) {


    $match = "10.2.91.52"
    $replacement = "localhost"

    $_ -creplace "10.2.91.52", $replacement


   }
   
   } |  Set-Content $filename


Remove Full Access permissions from shared folders with exceptions

$
0
0

Hi All,

Basically at my new work we have a shared network area with individual folders for each department. Each folder has multiple sub folders. The problem is the previous manager assigned 'full access' security rights on each folder and sub folder to absolutely everyone, including the 'everyone' group. I'd like to change the 'full access' security permissions to modify, but not for certain security groups like domain admins and certain other security groups.

I have some code in PowerShell that gives me a list of which groups have full access permissions but I need to be able to take that list and change them to modify.

I have the following code in powershell that outputs all groups with full access permissions to a folder that isn't in an except list. What I want to do is for each of the the groups it find, to change the 'Full Access' permissions to 'Modify', but I can't seem to find a way to do it.

$path ="\\srv-shared\sharedfolders"
$ExcludeUsers ='Domain\Domain Admins','NT AUTHORITY\SYSTEM','BUILTIN\Administrator','domain\Administrator'# Create regex-pattern to match all excluded users
$ExcludeUsersRegex =($ExcludeUsers |%{[regex]::Escape($_)})-join '|'Get-Childitem $path -Recurse-Directory|ForEach-Object{
    $file = $_Get-Acl-Path $file.FullName|Select-Object-ExpandPropertyAccess|Where-Object{
            $_.IdentityReference-notmatch $ExcludeUsersRegex -and
            $_.AccessControlType-eq "Allow"-and
            $_.FileSystemRights-eq "FullControl"}|ForEach-Object{#Foreach ACLNew-Object psobject -Property@{Path= $file.FullName
                ACL  = $_.IdentityReference}}}|Select-Object-PropertyPath, ACL |Export-Csv e:\check_acl.csv -NoTypeInformation

It would probably sit in the '#foreach acl' section but I'm having trouble getting it to work.

Any help is greatly appreciated.

Mailbox notification script

$
0
0

Hi everyone I have script for notifcate users about their mailbox, Users have different mailbox size, some users have 2gb mailbox size some 4gb, I need this script send notification when users reach 1.9 gb and 3.9 gb, can I change this script as I need?script I pasted below:

If ((Get-PSSnapin | where {$_.Name -match “Exchange.Management”}) -eq $null)
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
}
$toArray=Get-Mailboxdatabase db01 | Get-Mailbox | foreach-object {$email = $_.primarysmtpaddress; $_ | Get-MailboxStatistics | Where {$_.TotalItemSize.Value.ToMB() -gt 1900 } | select @{ expression={$email}}}
$toArray=Get-Mailboxdatabase db02 | Get-Mailbox | foreach-object {$email = $_.primarysmtpaddress; $_ | Get-MailboxStatistics | Where {$_.TotalItemSize.Value.ToMB() -gt 1900 } | select @{ expression={$email}}}
$from= “Administartor@test.local”
Foreach ($to in $toArray)
{
$s=[string]$to
[int]$Start = $s.IndexOf(“=”)
[int]$End = $s.IndexOf(“}”)
[string]$ss=$s.Substring($Start+1,$End-$start-1)
$Statistics = Get-MailboxStatistics $ss
$name = Get-Mailbox $ss
$messageParameters = @{
smtpServer = “192.168.199.1”
From = [string]$from
To = $ss
Subject = “Warning!”
Body = “Hi “+ $name + “.Your mailbox size is ” + $Statistics.TotalItemSize + ” Your mailbox size limit is 2000 MB. Please delete unnecessary emails to reduce size of your mailbox ”
}
Send-MailMessage @messageParameters -BodyAsHtml
}


System administrator



add a space between characters

$
0
0

Hi i would like to do the following 

i have a variable and would like to get the following.

Team one = Do nothing 
Teamone = change to "Team one"

thanks

Script to find a specific DHCP Option and listthe scope it is under

$
0
0

I have a Script see below it will scan and find the specific option I am looking for and list it, but it does not show me the server or scope id that it is found in, I have tried several modification to my script and have spent hours trying to fins a solution. 

I tried adding another for each statement and using the -Scopeid bit does not work.

Any help you can provide is much appreciated.

$server = Import-Csv -Path "C:\Scripts\dhcpserver.csv"

foreach ($Item in $server)
{

$DnsName = $item.DnsName

Get-DhcpServerv4OptionValue -ComputerName $DnsName | Where-Object OptionID -eq 67 }

How do I list all User Accounts with blank EmployeeID attribute?

$
0
0

Hello,

To list all AD User Accounts with a blank employeeid attribute, I've tried the following, but I get an unrecognized filter:

Get-Aduser -Filter 'employeeid -eq " "'

So if I cant get the previous command to work, how do I use a Where-Object on the following to list the accounts?  Thanks in advance.

get-aduser -Filter 'Name -like "*"' -properties employeeid -searchbase "ou=Users,dc=acme,dc=com" | Where-object


Thanks for your help! SdeDot
Viewing all 21975 articles
Browse latest View live


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