
    Vh=                        d dl mZ dZd dlZd dlZd dlZd dlZd dlZd dlm	c m
Z d dlZd dlmZmZ d dlmZ  ej$                  d      Zg dZddZddd	Z G d
 de      Zy)    )annotationsaL  
name: powershell
version_added: historical
short_description: Windows PowerShell
description:
- The only option when using 'winrm' or 'psrp' as a connection plugin.
- Can also be used when using 'ssh' as a connection plugin and the C(DefaultShell) has been configured to PowerShell.
extends_documentation_fragment:
- shell_windows
N)to_bytesto_text)	ShellBases'   \x00_\x00x((?:\x00[a-fA-F0-9]){4})\x00_)
PowerShellz
-NoProfilez-NonInteractivez-ExecutionPolicyUnrestrictedc                   d}| j                  |      dk(  r| S g }d}| j                  d      D ]  }|rd}|j                  d      }|dk(  r#|j                  |       |j                  |       @|d|dz    }||dz   d }	 |j                  d       	 t        |      }	|j                  |	       |r|j                  |       ||k(  rd}|j                  |        |r|j                  |       d
j                  |      S # t        $ r% |j                  d	      }|j                  d      }Y w xY w# t        $ r& |j                  |       |j                  |       Y 1w xY w)a  Replace CLIXML with stderr data.

    Tries to replace an embedded CLIXML string with the actual stderr data. If
    it fails to parse the CLIXML data, it will return the original data. This
    will replace any line inside the stderr string that contains a valid CLIXML
    sequence.

    :param bytes stderr: The stderr to try and decode.

    :returns: The stderr with the decoded CLIXML data or the original data.
    s   #< CLIXML
FT   </Objs>N   utf-8cp437    )	find
splitlinesappenddecodeUnicodeDecodeErrorencode_parse_clixml	Exceptionjoin)
stderrclixml_headerlines	is_clixmllineend_idxclixml	remainingclixml_textdecoded_clixmls
             P/home/dcms/DCMS/lib/python3.12/site-packages/ansible/plugins/shell/powershell.py_replace_stderr_clixmlr$   $   sr    %M{{=!R'EI!!$' +I ii
+G"}]+T"-GaK(FWq[]+I
5g&
#!.v!6^,LL+ ]"I LLW+^ ]#88E?= & 5 %mmG4$++G4	5  # ]+T"	#s$   ?D /D1 +D.-D.1+E E c                   g }dd}| r>| j                  d      }| j                  d      }|dk(  s|dk(  rn|dz  }| || }| |d } t        j                  |      }t        j                  d|j
                        }|rd|j                  d	       d
nd}	|j                  d|	z        }
|
s|r|j                  d       |
D ]  }|j                  j                  dd      }||k7  r%|j                  xs dj                  d      }t        j                  t        ||      }|j                  |j                  dd              | r>t!        dj#                  |      d      S )z
    Takes a byte string like '#< CLIXML
<Objs...' and extracts the stream
    message encoded in the XML data. CLIXML is used by PowerShell to encode
    multiple objects in stderr.
    c                    | j                  d      }|j                  d      }t        j                  |j	                               S )N   	utf-16-be)groupr   base64	b16decodeupper)matchobj	match_hex
hex_strings      r#   rplcrz_parse_clixml.<locals>.rplcrz   s:    NN1%	%%k2

 0 0 233r   s   <Objs r   r
   r   Nz{(.*)}{r'   } z./%sSz
Sr(   surrogatepass)errors)r-   zre.Matchreturnbytes)r   ET
fromstringrematchtagr)   findallr   attribgettextr   sub_STRING_DESERIAL_FINDr   r   r   )datastreamr   r0   	start_idxr   current_elementr   namespace_match	namespaceentriesstring_entryactual_streamb_line	b_escapeds                  r#   r   r   l   sd    E4 IIi(	))J'?gm1y1GH~/((9fjj99Hb..q12"5b	..9!45 LL # 	PL(//33C>M&"''-255kBF4eVDILL))+o)NO	P- @ BGGEN?;;r   c                      e Zd Z e       ZdZdZdZdZdZ	d Z
d Zd Zd	 Zd
 Zd Zd ZddZddZddZd Zd ZddZd Zd Zd ZddZy)ShellModule
powershellzPtry { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding } catch {}z> $null;Tc                     y)Nr3    )selfkwargss     r#   
env_prefixzShellModule.env_prefix   s    r   c           	         |D cg c]&  }t        j                  | j                  |            ( }}t        j                  |d   g|dd  D cg c]  }|j	                  d       c} S c c}w c c}w )Nr   r'   \)ntpathnormpath_unquoter   strip)rU   argsargpartsparts        r#   	join_pathzShellModule.join_path   sg    @DEs!34EE
 {{58OE!"I&NDtzz$'7&NOO F
 'Os   +A+A0
c                
   t         j                  j                  |j                               }t         j                  j	                  |j                               \  }}|j                         dvr|dz   S |j                         S )N).ps1z.exerd   )ospathbasenamer]   splitextlower)rU   pathname	base_namenameexts        r#   get_remote_filenamezShellModule.get_remote_filename   sb    GG$$X^^%56	GG$$Y__%67	c99;..&=   r   c                l    | j                  |      }|j                  d      xs |j                  d      S )N/rY   )r\   endswith)rU   rf   s     r#   path_has_trailing_slashz#ShellModule.path_has_trailing_slash   s-    }}T"}}S!8T]]4%88r   c                    t        d      )Nz'chmod is not implemented for PowershellNotImplementedError)rU   pathsmodes      r#   chmodzShellModule.chmod       !"KLLr   c                    t        d      )Nz'chown is not implemented for Powershellrt   )rU   rv   users      r#   chownzShellModule.chown   ry   r   c                    t        d      )Nz/set_user_facl is not implemented for Powershellrt   )rU   rv   r{   rw   s       r#   set_user_faclzShellModule.set_user_facl   s    !"STTr   c                    | j                  | j                  |            }|r| j                  d|z        S | j                  d|z        S )Nz!Remove-Item '%s' -Force -Recurse;zRemove-Item '%s' -Force;_escaper\   _encode_script)rU   rf   recurses      r#   removezShellModule.remove   sK    ||DMM$/0&&'NQU'UVV&&'E'LMMr   Nc                ,   |s| j                   j                         }| j                  | j                  |            }| j                  |r|n| j	                  d            }d| j
                   d| d| d}| j                  |j                               S )N
remote_tmpz	
        zG
        $tmp_path = [System.Environment]::ExpandEnvironmentVariables('zB')
        $tmp = New-Item -Type Directory -Path $tmp_path -Name 'z:'
        Write-Output -InputObject $tmp.FullName
        )	__class___generate_temp_dir_namer   r\   
get_option_CONSOLE_ENCODINGr   r]   )rU   basefilesystemrw   tmpdir
basetmpdirscripts          r#   mkdtempzShellModule.mkdtemp   s     ~~==?H<<h 78\\F&8UV
				  !GGQl S@@Hz J	 ""6<<>22r   c                    | j                  |      }|dk(  rd}n=|j                  d      rd| j                  |dd        z  }nd| j                  |      z  }| j                  | j                   d|       S )N~z Write-Output (Get-Location).Pathz~\z)Write-Output ((Get-Location).Path + '%s')r'   zWrite-Output '%s'z; )r\   
startswithr   r   r   )rU   user_home_pathusernamer   s       r#   expand_userzShellModule.expand_user   s     ~6S 7F&&u-@4<<P^_`_aPbCccF(4<<+GGF""d&<&<%=Rx#HIIr   c                n    | j                  | j                  |            }d|z  }| j                  |      S )Nz
            If (Test-Path '%s')
            {
                $res = 0;
            }
            Else
            {
                $res = 1;
            }
            Write-Output '$res';
            Exit $res;
         r   )rU   rf   r   s      r#   existszShellModule.exists  s=    ||DMM$/0  ""6**r   c                    | j                  | j                  |            }dt        |      z  }| j                  |      S )Na}  
            If (Test-Path -PathType Leaf '%(path)s')
            {
                $sp = new-object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider;
                $fp = [System.IO.File]::Open('%(path)s', [System.IO.Filemode]::Open, [System.IO.FileAccess]::Read);
                [System.BitConverter]::ToString($sp.ComputeHash($fp)).Replace("-", "").ToLower();
                $fp.Dispose();
            }
            ElseIf (Test-Path -PathType Container '%(path)s')
            {
                Write-Output "3";
            }
            Else
            {
                Write-Output "1";
            }
        )rf   )r   r\   dictr   )rU   rf   r^   rV   r   s        r#   checksumzShellModule.checksum  sA    ||DMM$/0  o!" ""6**r   c                   t        j                  dd      }|dk(  r| j                  |dd      S t        j                  |d      }t        t        t        |            }|r|j                         dk(  rm| j                  |d         j                         j                  d	      sd
| j                  |d         z  |d<   d|d   z   dz   | j                  |dd      z   }|S |r'|j                  d      r|j                  d|dd         n*|s(| j                  |d         |d<   |j                  |       d|ddj                  |      d}| j                  |d      S )Nzansible.executor.powershellzbootstrap_wrapper.ps1r3   F)r   strict_modepreserve_rc)posixz#!powershellr   rd   z"%s.ps1"ztype z | z#!   z/
            Try
            {
                z
                 a  
            }
            Catch
            {
                $_obj = @{ failed = $true }
                If ($_.Exception.GetType)
                {
                    $_obj.Add('msg', $_.Exception.Message)
                }
                Else
                {
                    $_obj.Add('msg', $_.ToString())
                }
                If ($_.InvocationInfo.PositionMessage)
                {
                    $_obj.Add('exception', $_.InvocationInfo.PositionMessage)
                }
                ElseIf ($_.ScriptStackTrace)
                {
                    $_obj.Add('exception', $_.ScriptStackTrace)
                }
                Try
                {
                    $_obj.Add('error_record', ($_ | ConvertTo-Json | ConvertFrom-Json))
                }
                Catch
                {
                }
                Echo $_obj | ConvertTo-Json -Compress -Depth 99
                Exit 1
            }
        )r   )pkgutilget_datar   shlexsplitlistmapr   ri   r\   rq   r   insertr   r   )	rU   
env_stringshebangcmdarg_pathbootstrap_wrapper	cmd_partswrapper_cmdr   s	            r#   build_module_commandz ShellModule.build_module_command&  si   #,,-JLcd "9&&.?U`e&ff KK51	Wi01	w}}.8==1.446??G)DMM)A,,GG	!!IaL0584;N;NVguz  IN;N  <O  OK++D1Q,==16IaLX&H 388I.G#0H ""6u"==r   c                    d|z  S )Nz& %s; exit $LASTEXITCODErT   )rU   r   s     r#   wrap_for_execzShellModule.wrap_for_execc  s    )C//r   c                    t        |xs d      }t        j                  d|      }|r|j                  d      S t        j                  d|      }|r|j                  d      S |S )z5Remove any matching quotes that wrap the given value.r3   z^\s*?\'(.*?)\'\s*?$r'   z^\s*?"(.*?)"\s*?$)r   r;   r<   r)   )rU   valuems      r#   r\   zShellModule._unquotef  sY    $HH+U3771:HH)51771:r   c                L    t        j                  d      j                  d|      S )z9Return value escaped for use in PowerShell single quotes.u   (['‘’‚‛])z\1\1)r;   compilerB   )rU   r   s     r#   r   zShellModule._escapeq  s!     zz:;??	5QQr   c                   t        |      }|dk(  rt        ddgz   }n|rd|z  }|rd|z  }dj                  |j                         D cg c]#  }|j	                         s|j	                         % c}      }t        t        j                  |j                  d            d      }t        d|gz   }|r|S d	j                  |      S c c}w )
z?Convert a PowerShell script to a single base64-encoded command.-z-Commandz"Set-StrictMode -Version Latest
%szz%s
If (-not $?) { If (Get-Variable LASTEXITCODE -ErrorAction SilentlyContinue) { exit $LASTEXITCODE } Else { exit 1 } }

z	utf-16-ler   z-EncodedCommandr   )r   _common_argsr   r   r]   r*   	b64encoder   )rU   r   as_listr   r   r   xencoded_scripts           r#   r   zShellModule._encode_scriptw  s    T>$
C'88I @6I  [YY63D3D3FTa!'')	TUF$V%5%5fmmK6P%QSZ[N$(9>'JJIxx	""  Us   CC)F)NFNN)r3   )N)FTT)__name__
__module____qualname__	frozensetCOMPATIBLE_SHELLSSHELL_FAMILYr   _SHELL_REDIRECT_ALLNULL
_SHELL_AND_IS_WINDOWSrW   rb   rn   rr   rx   r|   r~   r   r   r   r   r   r   r   r\   r   r   rT   r   r#   rP   rP      s    
 "L k'J KP!9
MMUN3 J+ +*;>z0	R#r   rP   )r   r8   r7   r8   )Error)rD   r8   rE   strr7   r8   )
__future__r   DOCUMENTATIONr*   re   r;   r   r   xml.etree.ElementTreeetreeElementTreer9   rZ   +ansible.module_utils.common.text.convertersr   r   ansible.plugins.shellr   r   rC   r   r$   r   rP   rT   r   r#   <module>r      se    #	  	 	   " "  I +
 #

#NO bEP7<tf#) f#r   