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

Unable to Enter-PSSession to remote VM which is not in domain

$
0
0

I tried all solution i saw online.

on the VM i dd "Enable-PSRemoting -Force"

then when i use  "Get-Service winrm" i get the service is running.

i also used winrm s winrm/config/client '@{TrustedHosts="$local machine"}' at the VM and "Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force"

on the local machine i use the command "Enter-PSSession -ComputerName $RemoteComputer -Credential $Creds"

and get:

Enter-PSSession : Connecting to remote server VM01 failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
At line:8 char:1
+ Enter-PSSession -ComputerName $RemoteComputer -Credential $Creds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (VM01:String) [Enter-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed
 



GetSecurityDescriptor from WMI with nonexisting user in result list

$
0
0

I have a script with which I can add users/groups to the security settings of a WMI class. This script run's fine except when a nonexisting user has access tot the WMI class

The problem part of the script is the first line below

$output = Invoke-WmiMethod -Namespace root/cimv2 -ComputerName computer1 -Path "__systemsecurity=@" -Name GetSecurityDescriptor
$acl = $output.Descriptor
$acl.DACL

When I run this script while a nonexisting user has access to the WMI class, I get an "Unexecpted Error". When I remove this user (S-1-5-21-xxxxxxxxxxxxx) through "Computer Manager", "WMI Control", "Properties", "Security", the script runs fine.

Is there a method to remove nonexisting users from WMI Classes, or to skip this user.

The error I get is:

Invoke-WmiMethod : Unexpected error
At line:1 char:18
+        $output = Invoke-WmiMethod -Namespace root -ComputerName computer1 -Path  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Invoke-WmiMethod], ManagementException
    + FullyQualifiedErrorId : InvokeWMIManagementException,Microsoft.PowerShell.Commands.InvokeWmiMethod

Enable Active Directory Recycle Bin

$
0
0

Dears

I have two domain controllers (DC1 , DC2 ) .

DC1 has the RID, PCD, Infrastructure Roles.

DC2 Has the Schema master and domain naming roles.

in DC1 i can open AD administrative Center , when i click on enable AD Recycle Bin i get the below Error .

Enable-ADOptionalFeature : Unable to contact the server. This may be because this server does not exist, it is
currently down, or it does not have the Active Directory Web Services running.

I tried too many things but nothing help me ( i got the same error when using Powers hell ).

On DC2 when I am trying to open the AD administrative Center i got the below Error

cannot connect to any domain try again when the connection is available

i can ping the names for each server all DNS setting is correct

please if anyone face the same problem and solve it  kindly reply to me

Issue with Do until loop

$
0
0

I have used the below selection based script. If I type Q its returning & if I type anything else apart from 1,2,3 it will display 'wrong output'. But if I type 1 it moves to next stage but displays 'wrong input'.

My question is why the script is displaying 'wrong input' when my selection is 1?

cls
do
{
Write-Host "================ LIST ================"  
Write-Host "Press 1 for A"
Write-Host "Press 2 for B"
Write-Host "Press 3 for C"
Write-Host "Press 'Q' to quit."
$selection = Read-Host "Please make a selection"

if ($selection -eq 'q') {return}
elseif ($selection -ne 1 -or $selection -ne 2 -or $selection -ne 3) { 'wrong input'}

}
until ($selection -eq 1 -or $selection -eq 2 -or $selection -eq 3)

Write-Host "================ List 2 ================"  
Write-Host "Press 1 for ABC "
Write-Host "Press 2 for PQR"
Write-Host "Press 3 for XYZ"

SCRIPT OUTPUT:

================ LIST ================
Press 1 for A
Press 2 for B
Press 3 for C
Press 'Q' to quit.
Please make a selection: 4
wrong input
================ LIST ================
Press 1 for A
Press 2 for B
Press 3 for C
Press 'Q' to quit.
Please make a selection: 1
wrong input
================ List 2 ================
Press 1 for ABC 
Press 2 for PQR
Press 3 for XYZ


Can someone explain this - get-aduser displays passwordneverexpires as false ( this mean the password expires)

$
0
0

Can someone explain this - get-aduser displays passwordneverexpires as false ( this mean the password expires)
from the same powershell window i type net user <uesrname> /dom  and the password expires is set to Never (this means password does not expire)
There is conflicting information - my reports for aduser is misleading - sample below

*************************************************

get-aduser christopher.ellis -properties passwordneverexpires

Enabled              : True
GivenName            : Christopher
Name                 : Christopher.Ellis
PasswordNeverExpires : False
SamAccountName       : christopher.ellis

************************************************************
net user christopher.ellis /domain
The request will be processed at a domain controller for domain XXXXXXXX.ca

User name                    christopher.ellis
Country/region code          (null)
Account active               Yes
Account expires              Never

Password last set            9/20/2018 2:11:28 PM
Password expires             Never
Password changeable          9/20/2018 2:11:28 PM
Password required            Yes

Thank you for shedding some light on this issue

Powershell comand to share calendar -- no matter the language used

$
0
0

I now need to review and reset the calendar permissions so that every user has Reviewer permissions. 

I have several users that are not using the English (US) names for there folders.

Can someone help?


repeat script options

$
0
0

I'm a powershell nube that needs some help.

I have a script that works, basically its creating network locations in windows 10 to replace mapped drives.

It uses two variables, one for the name of the location, and one for the UNC path of the target.

I would like to create a single script that runs through this process several times with different values for the two variables each time.

Is there a more efficient way to do this beyond just copy/paste the entire process and changing the variable values?  some way to repeat but with different values?

    $name='Name'
    $Target='\\servername\sharename'

    $networkshortcut_name = $Name
    $networkshortcut_target = $Target

    $networkshortcuts_path = [Environment]::GetFolderPath('NetworkShortcuts')

    $networkshortcut_path = "$networkshortcuts_path\$networkshortcut_name"
    $desktopini_path = "$networkshortcut_path\desktop.ini"
    $targetlnk_path = "$networkshortcut_path\target.lnk"

    $desktopini_text = "[.ShellClassInfo]`r`nCLSID2={0AFACED1-E828-11D1-9187-B532F1E9575D}`r`nFlags=2"

    if( Test-Path -Path $networkshortcut_path -PathType Container )
    {
        Remove-Item -Path $networkshortcut_path -Recurse -Force
    }

    [void](New-Item -Path $networkshortcut_path -ItemType directory)

    Set-ItemProperty -Path $networkshortcut_path -Name Attributes -Value 1

    Out-File -FilePath $desktopini_path -InputObject $desktopini_text -Encoding ascii

    Set-ItemProperty -Path $desktopini_path -Name Attributes -Value 6

    $WshShell = New-Object -com WScript.Shell
    $Shortcut = $WshShell.CreateShortcut($targetlnk_path)
    $Shortcut.TargetPath = $networkshortcut_target
    $Shortcut.Save()

any help would be appreciated

Get partition style info for multiple computers

$
0
0

Dears,

I`m trying to get partition style info for multiple computers.

I have a list of computers = 1.csv

$comps = import-csv C:\tmp\1.csv
$result = ForEach-Object{  
   gwmi -Computer $comp -query "Select * from Win32_DiskPartition WHERE Index = 0" | 
   Select-Object DiskIndex, @{Name="GPT";Expression={$_.Type.StartsWith("GPT")}}
    }

I got an error: gwmi : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

But when I`m writing computers name insteed $comp , it works.

Could you help me.


Running a Script as a different user throws 'A parameter cannot be found that matches parameter name 'Credential'.'

$
0
0

This has happened for a couple of scripts that I have tried to run.

We have a separate domain user that we use to schedule tasks with. This user has all of the permissions that it needs to access the script path and run the script. When I pass this command:

& "C:\ScheduledTasks\RunMemberDBAutomation.ps1"

I get back this error:

Import-Module : A parameter cannot be found that matches parameter name 'Credential'.
At C:\ScheduledTasks\RunMemberDBAutomation.ps1:29 char:1+ Import-Module SCCMemberDB+ ~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Import-Module], ParameterBindingException+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

As you can see, I'm not naming the Credential parameter when I call Import-Module, but the error claims I am wrongfully doing so.

Has anyone else seen this before? It's not the first time for me and I've found no clues as to why.

Thanks.

ConvertFrom-JSON

$
0
0

Hi there,

I'm a PS newbie here and my Google-Foo isn't really working.

$RequestURL = 'https://mtgjson.com/json/version-full.json'

$LatestVersion = Invoke-WebRequest $RequestURL | ConvertFrom-JSON | SELECT Version


It returns:

{"version": "3.19.2"
}

Now, how do I get to the value 3.19.2 

Tried Googling and searching the forums but my Foo <g class="gr_ gr_363 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="363" id="363">isnt</g> working tonight!

Regards,

Dave.

Azure Blob Store - downloading a file from another website

$
0
0

Hi there.

I can see a lot of tutorials that are showing how to upload a file a computer to Azure Blob store with PowerShell.

However, I would like to connect to a website <g class="gr_ gr_144 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace" data-gr-id="144" id="144">url</g> is a link to a zip file and download that into the Blob store unzipped. Is this possible?

If you can point me into the direction of <g class="gr_ gr_335 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="335" id="335">tutorial</g> or a quick demo it'd be appreciated. I can't <g class="gr_ gr_386 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" data-gr-id="386" id="386">seem</g> find to find the right words for Google tonight!

Regards,

Dave

Invoke-RestMethod Issues

$
0
0

I am trying to connect to an external api website. I don't know details around how REST/JSON works, but I want to use powershell to download a csv file via GET method. I could successfully connect via CURL, but with powershell I cannot, and am exhausted.

CURL:

curl.exe -v -H "Accept: application/json" -u APIKEY: "https://"

Powershell:

Invoke-RestMethod -Uri 'https://' -Headers @{"AUTHORIZATION"="Basic "} -Method Get

I always receive following error:

the underlying connection was closed an unexpected error occurred on a send and the underlying connection was closed an unexpected error occurred on a receive

I tried using following script for certificate:

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

Source: http://stackoverflow.com/questions/11696944/powershell-v3-invoke-webrequest-https-error

still no luck.

Can someone help me understand what I am doing wrong?

Update# 2:

Basic is followed by Base64Encoded API KEY. This is what I see when I use the API Web, the one website provides:

{
"Accept": "application/json",
"Authorization": "Basic Base64Encode",
"Content-Length": 0,
"x-forwarded-for": "Source IP"
}

I upgraded to v4

PS C:\> $PSVersionTable.PSVersion

Major Minor Build Revision
—– —– —– ——–
4 0 -1 -1

and also used:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

since TLS1.2 is the requirement, still same error:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.
At line:1 char:1
+ Invoke-RestMethod -Method Get -Uri 'https:////// ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], We
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

If I don't use https, then it says:

Unable to connect to the remote server

Enable Movement of Form Window

$
0
0

Hi,

I have the PowerShell code below which uses a form to display a message in a 'on top' window, please can someone tell me how I can make the message (form) window movable by the user?

At the moment the form window is static and cannot be moved - I want the form window to stay 'top most' but to allow users to be able to move the window...

$MessageTitle="Update Running..."
$MessageText="Update in progress, do not shutdown or disconnect..."
Add-Type -AssemblyName System.Windows.Forms    
#Build Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = $MessageTitle
$objForm.TopMost = $true
$objForm.AutoSize = $true
$objForm.AutoScroll = $true
$objForm.AutoSizeMode = "GrowAndShrink"
$objForm.startposition = "CenterScreen"
$objForm.MinimizeBox = $False
$objForm.MaximizeBox = $False
$objForm.WindowState = "Normal"
$objForm.SizeGripStyle = "Hide"
$objForm.ShowInTaskbar = $False
$Font = New-Object System.Drawing.Font("Arial",24,[System.Drawing.FontStyle]::Italic)
$objForm.Font = $Font
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Text = $MessageText
$objLabel.AutoSize = $true
$objForm.Controls.Add($objLabel)
$objForm.Show()| Out-Null

PowerShell v6 EapConfigXmlStream & Set-VpnConnectionIPsecConfiguration Issues in VPNClient Module

$
0
0

I am trying to add a VPN connection in PowerShell and figured out all the other switches, but I am new to PowerShell and can't find anything that I can understand about EapConfigXmlStream and without it in the command the command fails.

PS C:\Windows\system32> Add-VpnConnection -Name Test-VPN -ServerAddress "URL" -TunnelType L2tp -EncryptionLevel Maximum -AuthenticationMethod MsChapv2 -SplitTunneling $True -AllUserConnection $False -L2tpPsk "Key" -RememberCredential $False -UseWinLogonCredential $False -EapConfigXmlStream  -PassThru

Add-VpnConnection : Missing an argument for parameter 'EapConfigXmlStream'. Specify a parameter of type 'System.Xml.XmlDocument' and try again.
At line:1 char:280
+ ... tial $False -UseWinLogonCredential $False -EapConfigXmlStream  -PassT ...
+                                               ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Add-VpnConnection], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Add-VpnConnection

I am using MsChapv2 in the Win 10 Pro client and not using any EAP setting.

I also tried setting it up manually in Win 10 Pro and modifying it with the following only to get:

PS C:\Windows\system32> Set-VpnConnectionIPsecConfiguration -ConnectionName Castle_VPN -AuthenticationTransformConstants None -CipherTransformConstants AES256 -DHGroup Group14 -EncryptionMethod AES256 -IntegrityCheckMethod SHA256 -PfsGroup PFS2 -AllUserConnection $False -PassThru True

Set-VpnConnectionIPsecConfiguration : A positional parameter cannot be found that accepts argument 'False'.
At line:1 char:1
+ Set-VpnConnectionIPsecConfiguration -ConnectionName Castle_VPN -Authe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-VpnConnectionIPsecConfiguration], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Set-VpnConnectionIPsecConfiguration

I have all the hardening settings working in the client except I want to bump SHA 1 up to SHA 256, so getting this Set-VpnConnectionIPsecConfiguration to work gets me where I want to go per a security post I found. 

Then using another command got:

PS C:\Windows\system32> Set-VpnConnection -Name Castle_VPN -ServerAddress castlesedona.dlinkddns.com -TunnelType L2tp -EncryptionLevel Maximum -AuthenticationMethod MsChapv2 -SplitTunneling $True -AllUserConnection $False -L2tpPsk "Key" -RememberCredential $False -UseWinlogonCredential $False -EapConfigXmlStream  -IdleDisconnectSeconds 1800 -PassThru

Set-VpnConnection : Missing an argument for parameter 'EapConfigXmlStream'. Specify a parameter of type 'System.Xml.XmlDocument' and try again.
At line:1 char:281
+ ... tial $False -UseWinlogonCredential $False -EapConfigXmlStream  -IdleD ...
+                                               ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-VpnConnection], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Set-VpnConnection



Additional Information: I added Registry entry:  HKLM\SYSTEM\CurrentControlSet\Services\RasMan\ NegotiateDH2048_AES256 Data Type:  Reg_DWORD Value:  2

KB3191566-x64 fails to install on sbs 2011 sp1

$
0
0

Hi.

Trying to install KB3191566-x64 (WMF 5.1) on 2011 sp1 (ver 6.1.7601) and fails after restart, at 100% of configuring!!! Reverts changes, restarts, tries automatically for 2nd time and at 100% of configuring, fails and reverts again. .NET framework 4.6.2 is installed.

The actual goal is to upgrade the powershell above v2 which is installed now, because it is needed for Azure backup (on premise, just files and folders).

Other installations/hotfixes before that (eg sp1, .net 4.6.2) installed without many problems.

Any suggestions?

Thanks in advance

Demetris





Script to find on which servers an account is logged into

$
0
0
Anyone has any script to find out on which servers a useraccount is logged on to. I want to logoff the session from all servers, before changing password to prevent account lockout later.

Move filenames based on pattern

$
0
0

I was trying to build a script to move specific files from one location to another. When I run this script with powershell it also moves files with the wrong pattern. For example below I would like to move specific file name which names start with 40001- or higher and less then 50000-. 

Get-ChildItem $path -file  | Where-Object { $_.Name -gt "40001+-*" -and $_.Name -lt "50000+-*" } | Move-Item -destination $path -whatif

If we have a look to the result, we can see that also filenames which didnt had to be moved like 432412... and 432416... are listed to move while only 40003... twice should had been moved. Can somebody tell me what I'm doing wrong?

Result: 

Mode                LastWriteTime         Length                 Name                                                                                                                      
----                -------------         ------ ----                                                                                                                      
-a----        24-5-2007     10:56         537510               40003-ABS-01022006.pdf                                                                                                    
-a----       28-11-2013     14:11         163500              40003-DRINK-04122013.pdf                                                                                                  
-a----        20-9-2018     14:37          40120                432412-cathver-10092018.pdf                                                                                               
-a----        11-9-2018     08:32         451972               432416-cathver-11092018.pdf  

powershell script

$
0
0

I heve a  script, How Can I change date in script I need user recieve notification in this format day/month/year/    but  users recieve in this format   month/day/year   date in server change as I need but it not work:

  # PSPwdExpires.ps1
# PowerShell script to find all user accounts where the password
# is about to expire in a specified number of days.
#
# ----------------------------------------------------------------------
# Copyright (c) 2011 Richard L. Mueller
# Hilltop Lab web site - http://www.rlmueller.net
# Version 1.0 - March 23, 2011
# Version 1.1 - April 6, 2011 - Added email function.
#
# This program assumes there is one password policy for the domain. The
# program finds all users whose password will expire in the specified
# period.
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the copyright owner above has no warranty, obligations,
# or liability for such use.

Trap {"Error: $_"; Break;}

# Specify number of days. Any users whose passwords expire within
# this many days after today will be processed.
$intDays = 1
$intDays = 3
$intDays = 5

# Email settings.
$Script:From = "notifications@x.com"
$Script:Subject = "Password Expiration Notice"
$Server = "192.168.x.x"
$Port = 25
$Client = New-Object System.Net.Mail.SmtpClient $Server, $Port
# You may need to provide credentials.
$Client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

Function SendEmail($To, $Body)
{
    $Message = New-Object System.Net.Mail.MailMessage `
        $Script:From, $To, $Script:Subject, $Body
    $Client.Send($Message)
}

# Retrieve Domain maximum password age policy, in days.
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$MPA = $Domain.maxPwdAge.Value
# Convert to Int64 ticks (100-nanosecond intervals).
$lngMaxPwdAge = $Domain.ConvertLargeIntegerToInt64($MPA)
# Convert to days.
$MaxPwdAge = -$lngMaxPwdAge/(600000000 * 1440)

# Determine the password last changed date such that the password
# would just now be expired. We will not process any users whose
# password has already expired.
$Now = Get-Date
$Date1 = $Now.AddDays(-$MaxPwdAge)

# Determine the password last changed date such the password
# will expire $intDays in the future.
$Date2 = $Now.AddDays($intDays - $MaxPwdAge)

# Convert from PowerShell ticks to Active Directory ticks.
$64Bit1 = $Date1.Ticks - 504911232000000000
$64Bit2 = $Date2.Ticks - 504911232000000000

$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"

# Filter on user objects where the password expires between the
# dates specified, the account is not disabled, password never
# expires is not set, password not required is not set.
# and password cannot change is not set.
$Searcher.Filter = "(&(objectCategory=person)(objectClass=user)" `
    + "(pwdLastSet>=" + $($64Bit1) + ")" `
    + "(pwdLastSet<=" + $($64Bit2) + ")" `
    + "(!userAccountControl:1.2.840.113556.1.4.803:=2)" `
    + "(!userAccountControl:1.2.840.113556.1.4.803:=65536)" `
    + "(!userAccountControl:1.2.840.113556.1.4.803:=32)" `
    + "(!userAccountControl:1.2.840.113556.1.4.803:=48))"

$Searcher.PropertiesToLoad.Add("sAMAccountName") > $Null
$Searcher.PropertiesToLoad.Add("DisplayName") > $Null
$Searcher.PropertiesToLoad.Add("pwdLastSet") > $Null
$Searcher.PropertiesToLoad.Add("mail") > $Null
$Searcher.PropertiesToLoad.Add("proxyAddresses") > $Null
$Searcher.SearchRoot = "LDAP://" + $Domain.distinguishedName

$Results = $Searcher.FindAll()
ForEach ($Result In $Results)
{
    $Name = $Result.Properties.Item("sAMAccountName")
    $DisplayName = $Result.Properties.Item("DisplayName")
    $PLS = $Result.Properties.Item("pwdLastSet")
    $Mail = $Result.Properties.Item("mail")
    $Addresses = $Result.Properties.Item("proxyAddresses")
    If ($PLS.Count -eq 0)
    {
        $Date = [DateTime]0
    }
    Else
    {
        # Interpret 64-bit integer as a date.
        $Date = [DateTime]$PLS.Item(0)
    }
    # Convert from .NET ticks to Active Directory Integer8 ticks.
    # Also, convert from UTC to local time.
    $PwdLastSet = $Date.AddYears(1600).ToLocalTime()
    # Determine when password expires.
    $PwdExpires = $PwdLastSet.AddDays($MaxPwdAge)

    # Determine email address.
    If ("$Mail" -eq "")
    {
        ForEach ($Address In $Addresses)
        {
            $Prefix = $Address.SubString(0, 5)
            If (($Prefix -ceq "SMTP:") -or ($Prefix -ceq "X400:"))
            {
                $Mail = $Address.SubString(5)
                Break
            }
        }
    }
    If ("$Mail" -ne "")
    {
        $Notice = " Hello $DisplayName,

xxxxxxxxxxxxxxxxxxxxxxxxx $Name sssssssssssssssss $PwdExpires. "
        SendEmail $Mail $Notice
        "Email sent to $Name ($Mail), password expires $PwdExpires"
    }
    Else
    {
        "$Name has no email, but password expires $PwdExpires"
        "DN: $DN"
    }
}


System administrator

Desired State Configuration issue

$
0
0

Hi everyone,

I am trying to create dsc config that will install domain and join server to a domain. My script is failing with error message 

PSDesiredStateConfiguration\node : Defining node 'node name' inside the current node is not allowed since node definitions cannot be nested.
At C:\DomainInstall.ps1:155 char:5
+     node $AllNodes.Where{$_.Role -eq 'Workgroup'}.NodeName {
+     ~~~~

+ CategoryInfo          : InvalidOperation: (:) [Write-Error], InvalidOperationException
    + FullyQualifiedErrorId : NestedNodeNotAllowed,PSDesiredStateConfiguration\node

I am not sure why it saying nesting when I have 2 separate node $AllNodes.Where{$_.Role -eq 'rolename'}.NodeName statements?

Configuration data example

AllNodes = @(
    @{
        NodeName                    = '*'
        RetryCount                  = 40
        RetryIntervalSec            = 50
        PSDscAllowPlainTextPassword = $True
     },

    @{
        NodeName             = '192.168.0.139'
        Role                 = 'Domain Controller'
        
      },
    
    @{
        NodeName             = '192.168.0.140'
        Role                 = 'Workgroup'
      },

    @{
        NodeName             = '192.168.0.141'
        Role                 = 'Workgroup'
      }

Then I have 2 $allnodes

node $AllNodes.Where{$_.Role -eq 'Domain Controller'}.NodeName
node $AllNodes.Where{$_.Role -eq 'Workgroup'}.NodeName

So I don't understand why it is saying Defining node 'node name' inside the current node when it is not

Issue with PS Script working on Windows 7 PCs but not Windows 10

$
0
0

I have this script to delete profiles older than X number of days and preserve some existing accounts.  It works well on Windows 7 computers but I get error messages when I try to run it on Windows 10 PCs.  I have attached the script and error messages.  Any help would be greatly appreciated.

Thanks,

Andy

$Profiles = Get-WmiObject -Class Win32_UserProfile
$NumDays = 60
$CutoffDate = (Get-Date).AddDays(-$NumDays)
$LogFile = "C:\ProfileDeletion.log"
$ProtectedProfiles = "adachurchill","administrator","default","system","public"

#If a log file doesn't exist, create one
if (-not(Test-Path -Path $LogFile)){
    New-Item -Path $LogFile -ItemType File | Out-Null
}

#Cycle thru each profile and delete it if it's older than the cutoff date
foreach ($Profile in $Profiles){
    $Name = $Profile.LocalPath.Split("\")[2]
    $StrLastUse = $Profile.LastUseTime.Substring(0,8)
    $LastUseDay = [datetime]::ParseExact($StrLastUse,"yyyyMMdd",$null)
    $DateTimeString = Get-Date -Format u
    if (($Profile.Special -eq $false) -and 
        ($LastUseDay -lt $CutoffDate) -and 
        ($ProtectedProfiles -notcontains $Name)){
        try {
            $Profile.Delete()"$DateTimeString`t$Name`t`tDelete Successful" | Out-File -Encoding ASCII -FilePath $LogFile -Append
        } catch {"$DateTimeString`t$Name`t`tDelete Failed" | Out-File -Encoding ASCII -FilePath $LogFile -Append
        }
    }
}

The Error messages.

You cannot call a method on a null-valued expression.
At line:15 char:5
+     $StrLastUse = $Profile.LastUseTime.Substring(0,8)+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At line:15 char:5+     $StrLastUse = $Profile.LastUseTime.Substring(0,8)+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At line:15 char:5+     $StrLastUse = $Profile.LastUseTime.Substring(0,8)+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException+ FullyQualifiedErrorId : InvokeMethodOnNull

Viewing all 21975 articles
Browse latest View live


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